File size: 23,479 Bytes
eefe2da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
'use strict';
//parse Empty Node as self closing node
import buildFromOrderedJs from './orderedJs2Xml.js';
import getIgnoreAttributesFn from "./ignoreAttributes.js";
import { Expression, Matcher } from 'path-expression-matcher';
import { safeComment, safeCdata, escapeAttribute, valToStr } from './util.js';
import { createValidator } from 'xml-naming';

const defaultOptions = {
  attributeNamePrefix: '@_',
  attributesGroupName: false,
  textNodeName: '#text',
  ignoreAttributes: true,
  cdataPropName: false,
  format: false,
  indentBy: '  ',
  suppressEmptyNode: false,
  suppressUnpairedNode: true,
  suppressBooleanAttributes: true,
  tagValueProcessor: function (key, a) {
    return a;
  },
  attributeValueProcessor: function (attrName, a) {
    return a;
  },
  preserveOrder: false,
  commentPropName: false,
  unpairedTags: [],
  entities: [
    { regex: new RegExp("&", "g"), val: "&" },//it must be on top
    { regex: new RegExp(">", "g"), val: ">" },
    { regex: new RegExp("<", "g"), val: "&lt;" },
    { regex: new RegExp("\'", "g"), val: "&apos;" },
    { regex: new RegExp("\"", "g"), val: "&quot;" }
  ],
  processEntities: true,
  stopNodes: [],
  // transformTagName: false,
  // transformAttributeName: false,
  oneListGroup: false,
  maxNestedTags: 100,
  jPath: true,  // When true, callbacks receive string jPath; when false, receive Matcher instance
  sanitizeName: false  // false = allow all names as-is (default, backward-compatible).
  // Set to a function (name, { isAttribute, matcher }) => string to
  // validate/sanitize tag and attribute names. Throw inside the function
  // to reject an invalid name.
};

export default function Builder(options) {
  this.options = Object.assign({}, defaultOptions, options);

  // Convert old-style stopNodes for backward compatibility
  // Old syntax: "*.tag" meant "tag anywhere in tree"
  // New syntax: "..tag" means "tag anywhere in tree"
  if (this.options.stopNodes && Array.isArray(this.options.stopNodes)) {
    this.options.stopNodes = this.options.stopNodes.map(node => {
      if (typeof node === 'string' && node.startsWith('*.')) {
        // Convert old wildcard syntax to deep wildcard
        return '..' + node.substring(2);
      }
      return node;
    });
  }

  // Pre-compile stopNode expressions for pattern matching
  this.stopNodeExpressions = [];
  if (this.options.stopNodes && Array.isArray(this.options.stopNodes)) {
    for (let i = 0; i < this.options.stopNodes.length; i++) {
      const node = this.options.stopNodes[i];
      if (typeof node === 'string') {
        this.stopNodeExpressions.push(new Expression(node));
      } else if (node instanceof Expression) {
        this.stopNodeExpressions.push(node);
      }
    }
  }

  if (this.options.ignoreAttributes === true || this.options.attributesGroupName) {
    this.isAttribute = function (/*a*/) {
      return false;
    };
  } else {
    this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes)
    this.attrPrefixLen = this.options.attributeNamePrefix.length;
    this.isAttribute = isAttribute;
  }

  this.processTextOrObjNode = processTextOrObjNode

  if (this.options.format) {
    this.indentate = indentate;
    this.tagEndChar = '>\n';
    this.newLine = '\n';
  } else {
    this.indentate = function () {
      return '';
    };
    this.tagEndChar = '>';
    this.newLine = '';
  }
}

/**
 * Detect XML version from the ?xml declaration at the root of a plain-object input.
 * Checks both attributesGroupName and flat attribute forms.
 * Returns '1.0' if no declaration is found.
 */
function detectXmlVersionFromObj(jObj, options) {
  const decl = jObj['?xml'];
  if (decl && typeof decl === 'object') {
    // attributesGroupName path e.g. { '$$': { '@_version': '1.1' } }
    if (options.attributesGroupName && decl[options.attributesGroupName]) {
      const v = decl[options.attributesGroupName][options.attributeNamePrefix + 'version'];
      if (v) return v;
    }
    // flat attribute path e.g. { '@_version': '1.1' }
    const v = decl[options.attributeNamePrefix + 'version'];
    if (v) return v;
  }
  return '1.0';
}

/**
 * Resolve a tag or attribute name through sanitizeName if configured.
 * Validation via xml-naming's qName is performed first; the sanitizeName
 * callback is invoked only when the name is invalid. If sanitizeName is
 * false (default), no validation occurs and the name is used as-is.
 *
 * @param {string}  name        - raw name from the JS object
 * @param {boolean} isAttribute - true when resolving an attribute name
 * @param {object}  options
 * @param {Matcher} matcher     - current matcher state (readonly from callback perspective)
 * @param {function} qNameValidator - function to validate tag names
 */
function resolveTagName(name, isAttribute, options, matcher, qNameValidator) {
  if (!options.sanitizeName) return name;
  if (qNameValidator(name)) return name;
  return options.sanitizeName(name, { isAttribute, matcher: matcher.readOnly() });
}

Builder.prototype.build = function (jObj) {
  if (this.options.preserveOrder) {
    return buildFromOrderedJs(jObj, this.options);
  } else {
    if (Array.isArray(jObj) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1) {
      jObj = {
        [this.options.arrayNodeName]: jObj
      }
    }
    // Initialize matcher for path tracking
    const matcher = new Matcher();
    const xmlVersion = detectXmlVersionFromObj(jObj, this.options);
    const qNameValidator = createValidator('qName', { xmlVersion });
    return this.j2x(jObj, 0, matcher, qNameValidator).val;
  }
};

Builder.prototype.j2x = function (jObj, level, matcher, qNameValidator) {
  let attrStr = '';
  let val = '';
  if (this.options.maxNestedTags && matcher.getDepth() >= this.options.maxNestedTags) {
    throw new Error("Maximum nested tags exceeded");
  }
  // Get jPath based on option: string for backward compatibility, or Matcher for new features
  const jPath = this.options.jPath ? matcher.toString() : matcher;

  // Check if current node is a stopNode (will be used for attribute encoding)
  const isCurrentStopNode = this.checkStopNode(matcher);

  for (let key in jObj) {
    if (!Object.prototype.hasOwnProperty.call(jObj, key)) continue;

    // Resolve the key through sanitizeName before any use.
    // Special keys (textNodeName, cdataPropName, commentPropName, attributeNamePrefix,
    // attributesGroupName, "?" PI tags) are exempt — they are builder-internal conventions,
    // not user-supplied XML names.
    const isSpecialKey = key === this.options.textNodeName
      || key === this.options.cdataPropName
      || key === this.options.commentPropName
      || (this.options.attributesGroupName && key === this.options.attributesGroupName)
      || this.isAttribute(key)
      || key[0] === '?';

    const resolvedKey = isSpecialKey
      ? key
      : resolveTagName(key, false, this.options, matcher, qNameValidator);

    if (typeof jObj[key] === 'undefined') {
      // supress undefined node only if it is not an attribute
      if (this.isAttribute(key)) {
        val += '';
      }
    } else if (jObj[key] === null) {
      // null attribute should be ignored by the attribute list, but should not cause the tag closing
      if (this.isAttribute(key)) {
        val += '';
      } else if (resolvedKey === this.options.cdataPropName || resolvedKey === this.options.commentPropName) {
        val += '';
      } else if (resolvedKey[0] === '?') {
        val += this.indentate(level) + '<' + resolvedKey + '?' + this.tagEndChar;
      } else {
        val += this.indentate(level) + '<' + resolvedKey + '/' + this.tagEndChar;
      }
    } else if (jObj[key] instanceof Date) {
      val += this.buildTextValNode(jObj[key], resolvedKey, '', level, matcher);
    } else if (typeof jObj[key] !== 'object') {
      //premitive type
      const attr = this.isAttribute(key);
      if (attr && !this.ignoreAttributesFn(attr, jPath)) {
        // Resolve the attribute name through sanitizeName
        const resolvedAttr = resolveTagName(attr, true, this.options, matcher, qNameValidator);
        attrStr += this.buildAttrPairStr(resolvedAttr, valToStr(jObj[key]), isCurrentStopNode);
      } else if (!attr) {
        //tag value
        if (key === this.options.textNodeName) {
          let newval = this.options.tagValueProcessor(key, valToStr(jObj[key]));
          val += this.replaceEntitiesValue(newval);
        } else {
          // Check if this is a stopNode before building
          matcher.push(resolvedKey);
          const isStopNode = this.checkStopNode(matcher);
          matcher.pop();

          if (isStopNode) {
            // Build as raw content without encoding
            const textValue = valToStr(jObj[key]);
            if (textValue === '') {
              val += this.indentate(level) + '<' + resolvedKey + this.closeTag(resolvedKey) + this.tagEndChar;
            } else {
              val += this.indentate(level) + '<' + resolvedKey + '>' + textValue + '</' + resolvedKey + this.tagEndChar;
            }
          } else {
            val += this.buildTextValNode(jObj[key], resolvedKey, '', level, matcher);
          }
        }
      }
    } else if (Array.isArray(jObj[key])) {
      //repeated nodes
      const arrLen = jObj[key].length;
      let listTagVal = "";
      let listTagAttr = "";
      for (let j = 0; j < arrLen; j++) {
        const item = jObj[key][j];
        if (typeof item === 'undefined') {
          // supress undefined node
        } else if (item === null) {
          if (resolvedKey[0] === "?") val += this.indentate(level) + '<' + resolvedKey + '?' + this.tagEndChar;
          else val += this.indentate(level) + '<' + resolvedKey + '/' + this.tagEndChar;
        } else if (typeof item === 'object') {
          if (this.options.oneListGroup) {
            // Push tag to matcher before recursive call
            matcher.push(resolvedKey);
            const result = this.j2x(item, level + 1, matcher, qNameValidator);
            // Pop tag from matcher after recursive call
            matcher.pop();

            listTagVal += result.val;
            if (this.options.attributesGroupName && item.hasOwnProperty(this.options.attributesGroupName)) {
              listTagAttr += result.attrStr
            }
          } else {
            listTagVal += this.processTextOrObjNode(item, resolvedKey, level, matcher, qNameValidator)
          }
        } else {
          if (this.options.oneListGroup) {
            let textValue = this.options.tagValueProcessor(resolvedKey, item);
            textValue = this.replaceEntitiesValue(textValue);
            textValue = valToStr(textValue);
            listTagVal += textValue;
          } else {
            // Check if this is a stopNode before building
            matcher.push(resolvedKey);
            const isStopNode = this.checkStopNode(matcher);
            matcher.pop();

            if (isStopNode) {
              // Build as raw content without encoding
              const textValue = valToStr(item);
              if (textValue === '') {
                listTagVal += this.indentate(level) + '<' + resolvedKey + this.closeTag(resolvedKey) + this.tagEndChar;
              } else {
                listTagVal += this.indentate(level) + '<' + resolvedKey + '>' + textValue + '</' + resolvedKey + this.tagEndChar;
              }
            } else {
              listTagVal += this.buildTextValNode(item, resolvedKey, '', level, matcher);
            }
          }
        }
      }
      if (this.options.oneListGroup) {
        listTagVal = this.buildObjectNode(listTagVal, resolvedKey, listTagAttr, level);
      }
      val += listTagVal;
    } else {
      //nested node
      if (this.options.attributesGroupName && key === this.options.attributesGroupName) {
        const Ks = Object.keys(jObj[key]);
        const L = Ks.length;
        for (let j = 0; j < L; j++) {
          // Resolve attribute names inside attributesGroupName
          const resolvedAttr = resolveTagName(Ks[j], true, this.options, matcher, qNameValidator);
          attrStr += this.buildAttrPairStr(resolvedAttr, valToStr(jObj[key][Ks[j]]), isCurrentStopNode);
        }
      } else {
        val += this.processTextOrObjNode(jObj[key], resolvedKey, level, matcher, qNameValidator)
      }
    }
  }
  return { attrStr: attrStr, val: val };
};

Builder.prototype.buildAttrPairStr = function (attrName, val, isStopNode) {
  if (!isStopNode) {
    val = this.options.attributeValueProcessor(attrName, valToStr(val));
    val = this.replaceEntitiesValue(val);
  }
  if (this.options.suppressBooleanAttributes && val === "true") {
    return ' ' + attrName;
  } else return ' ' + attrName + '="' + escapeAttribute(val) + '"';
}

function processTextOrObjNode(object, key, level, matcher, qNameValidator) {
  // Extract attributes to pass to matcher
  const attrValues = this.extractAttributes(object);

  // Push tag to matcher before recursion WITH attributes
  matcher.push(key, attrValues);

  // Check if this entire node is a stopNode
  const isStopNode = this.checkStopNode(matcher);

  if (isStopNode) {
    // For stopNodes, build raw content without entity encoding
    const rawContent = this.buildRawContent(object);
    const attrStr = this.buildAttributesForStopNode(object);
    matcher.pop();
    return this.buildObjectNode(rawContent, key, attrStr, level);
  }

  const result = this.j2x(object, level + 1, matcher, qNameValidator);
  // Pop tag from matcher after recursion
  matcher.pop();

  // PI/XML-declaration tags must never emit text content — route through
  // buildTextValNode which correctly ignores the text node for "?" tags.
  if (key[0] === '?') {
    return this.buildTextValNode('', key, result.attrStr, level, matcher);
  } else if (object[this.options.textNodeName] !== undefined && Object.keys(object).length === 1) {
    return this.buildTextValNode(object[this.options.textNodeName], key, result.attrStr, level, matcher);
  } else {
    return this.buildObjectNode(result.val, key, result.attrStr, level);
  }
}

// Helper method to extract attributes from an object
Builder.prototype.extractAttributes = function (obj) {
  if (!obj || typeof obj !== 'object') return null;

  const attrValues = {};
  let hasAttrs = false;

  // Check for attributesGroupName (when attributes are grouped)
  if (this.options.attributesGroupName && obj[this.options.attributesGroupName]) {
    const attrGroup = obj[this.options.attributesGroupName];
    for (let attrKey in attrGroup) {
      if (!Object.prototype.hasOwnProperty.call(attrGroup, attrKey)) continue;
      // Remove attribute prefix if present
      const cleanKey = attrKey.startsWith(this.options.attributeNamePrefix)
        ? attrKey.substring(this.options.attributeNamePrefix.length)
        : attrKey;
      attrValues[cleanKey] = escapeAttribute(attrGroup[attrKey]);
      hasAttrs = true;
    }
  } else {
    // Look for individual attributes (prefixed with attributeNamePrefix)
    for (let key in obj) {
      if (!Object.prototype.hasOwnProperty.call(obj, key)) continue;
      const attr = this.isAttribute(key);
      if (attr) {
        attrValues[attr] = escapeAttribute(obj[key]);
        hasAttrs = true;
      }
    }
  }

  return hasAttrs ? attrValues : null;
};

// Build raw content for stopNode without entity encoding
Builder.prototype.buildRawContent = function (obj) {
  if (typeof obj === 'string') {
    return obj; // Already a string, return as-is
  }

  if (typeof obj !== 'object' || obj === null) {
    return String(obj);
  }

  // Check if this is a stopNode data from parser: { "#text": "raw xml", "@_attr": "val" }
  if (obj[this.options.textNodeName] !== undefined) {
    return obj[this.options.textNodeName]; // Return raw text without encoding
  }

  // Build raw XML from nested structure
  let content = '';

  for (let key in obj) {
    if (!Object.prototype.hasOwnProperty.call(obj, key)) continue;

    // Skip attributes
    if (this.isAttribute(key)) continue;
    if (this.options.attributesGroupName && key === this.options.attributesGroupName) continue;

    const value = obj[key];

    if (key === this.options.textNodeName) {
      content += value; // Raw text
    } else if (Array.isArray(value)) {
      // Array of same tag
      for (let item of value) {
        if (typeof item === 'string' || typeof item === 'number') {
          content += `<${key}>${item}</${key}>`;
        } else if (typeof item === 'object' && item !== null) {
          const nestedContent = this.buildRawContent(item);
          const nestedAttrs = this.buildAttributesForStopNode(item);
          if (nestedContent === '') {
            content += `<${key}${nestedAttrs}/>`;
          } else {
            content += `<${key}${nestedAttrs}>${nestedContent}</${key}>`;
          }
        }
      }
    } else if (typeof value === 'object' && value !== null) {
      // Nested object
      const nestedContent = this.buildRawContent(value);
      const nestedAttrs = this.buildAttributesForStopNode(value);
      if (nestedContent === '') {
        content += `<${key}${nestedAttrs}/>`;
      } else {
        content += `<${key}${nestedAttrs}>${nestedContent}</${key}>`;
      }
    } else {
      // Primitive value
      content += `<${key}>${value}</${key}>`;
    }
  }

  return content;
};

// Build attribute string for stopNode (no entity encoding)
Builder.prototype.buildAttributesForStopNode = function (obj) {
  if (!obj || typeof obj !== 'object') return '';

  let attrStr = '';

  // Check for attributesGroupName (when attributes are grouped)
  if (this.options.attributesGroupName && obj[this.options.attributesGroupName]) {
    const attrGroup = obj[this.options.attributesGroupName];
    for (let attrKey in attrGroup) {
      if (!Object.prototype.hasOwnProperty.call(attrGroup, attrKey)) continue;
      const cleanKey = attrKey.startsWith(this.options.attributeNamePrefix)
        ? attrKey.substring(this.options.attributeNamePrefix.length)
        : attrKey;
      const val = attrGroup[attrKey];
      if (val === true && this.options.suppressBooleanAttributes) {
        attrStr += ' ' + cleanKey;
      } else {
        // stopNode content is raw, but the quote delimiter is always escaped
        // so a quote in the value cannot break out of the attribute (see orderedJs2Xml attr_to_str)
        attrStr += ' ' + cleanKey + '="' + escapeAttribute(val) + '"';
      }
    }
  } else {
    // Look for individual attributes
    for (let key in obj) {
      if (!Object.prototype.hasOwnProperty.call(obj, key)) continue;
      const attr = this.isAttribute(key);
      if (attr) {
        const val = obj[key];
        if (val === true && this.options.suppressBooleanAttributes) {
          attrStr += ' ' + attr;
        } else {
          // stopNode content is raw, but the quote delimiter is always escaped
          // so a quote in the value cannot break out of the attribute (see orderedJs2Xml attr_to_str)
          attrStr += ' ' + attr + '="' + escapeAttribute(val) + '"';
        }
      }
    }
  }

  return attrStr;
};

Builder.prototype.buildObjectNode = function (val, key, attrStr, level) {
  if (val === "") {
    if (key[0] === "?") return this.indentate(level) + '<' + key + attrStr + '?' + this.tagEndChar;
    else {
      return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar;
    }
  } else if (key[0] === "?") {
    // PI/XML-declaration tags never have body content — treat them like empty.
    return this.indentate(level) + '<' + key + attrStr + '?' + this.tagEndChar;
  } else {
    let tagEndExp = '</' + key + this.tagEndChar;
    let piClosingChar = "";

    if (key[0] === "?") {
      piClosingChar = "?";
      tagEndExp = "";
    }

    // attrStr is an empty string in case the attribute came as undefined or null
    if ((attrStr || attrStr === '') && val.indexOf('<') === -1) {
      return (this.indentate(level) + '<' + key + attrStr + piClosingChar + '>' + val + tagEndExp);
    } else if (this.options.commentPropName !== false && key === this.options.commentPropName && piClosingChar.length === 0) {
      return this.indentate(level) + `<!--${safeComment(val)}-->` + this.newLine;
    } else {
      return (
        this.indentate(level) + '<' + key + attrStr + piClosingChar + this.tagEndChar +
        val +
        this.indentate(level) + tagEndExp);
    }
  }
}

Builder.prototype.closeTag = function (key) {
  let closeTag = "";
  if (this.options.unpairedTags.indexOf(key) !== -1) { //unpaired
    if (!this.options.suppressUnpairedNode) closeTag = "/"
  } else if (this.options.suppressEmptyNode) { //empty
    closeTag = "/";
  } else {
    closeTag = `></${key}`
  }
  return closeTag;
}

Builder.prototype.checkStopNode = function (matcher) {
  if (!this.stopNodeExpressions || this.stopNodeExpressions.length === 0) return false;

  for (let i = 0; i < this.stopNodeExpressions.length; i++) {
    if (matcher.matches(this.stopNodeExpressions[i])) {
      return true;
    }
  }
  return false;
}

function buildEmptyObjNode(val, key, attrStr, level) {
  if (val !== '') {
    return this.buildObjectNode(val, key, attrStr, level);
  } else {
    if (key[0] === "?") return this.indentate(level) + '<' + key + attrStr + '?' + this.tagEndChar;
    else {
      return this.indentate(level) + '<' + key + attrStr + '/' + this.tagEndChar;
    }
  }
}

Builder.prototype.buildTextValNode = function (val, key, attrStr, level, matcher) {
  if (this.options.cdataPropName !== false && key === this.options.cdataPropName) {
    const safeVal = safeCdata(val);
    return this.indentate(level) + `<![CDATA[${safeVal}]]>` + this.newLine;
  } else if (this.options.commentPropName !== false && key === this.options.commentPropName) {
    const safeVal = safeComment(val);
    return this.indentate(level) + `<!--${safeVal}-->` + this.newLine;
  } else if (key[0] === "?") {//PI tag
    return this.indentate(level) + '<' + key + attrStr + '?' + this.tagEndChar;
  } else {
    // Normal processing: apply tagValueProcessor and entity replacement
    let textValue = this.options.tagValueProcessor(key, val);
    textValue = this.replaceEntitiesValue(textValue);
    // tagValueProcessor may return the raw value unchanged (default is identity), and
    // replaceEntitiesValue no-ops on non-strings, so a plain number can still reach here;
    // stringify it now, sign-preserving, before it's implicitly ToString'd below.
    textValue = valToStr(textValue);

    if (textValue === '') {
      return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar;
    } else {
      return this.indentate(level) + '<' + key + attrStr + '>' +
        textValue +
        '</' + key + this.tagEndChar;
    }
  }
}

Builder.prototype.replaceEntitiesValue = function (textValue) {
  if (textValue && textValue.length > 0 && this.options.processEntities) {
    for (let i = 0; i < this.options.entities.length; i++) {
      const entity = this.options.entities[i];
      textValue = textValue.replace(entity.regex, entity.val);
    }
  }
  return textValue;
}

function indentate(level) {
  return this.options.indentBy.repeat(level);
}

function isAttribute(name /*, options*/) {
  if (name.startsWith(this.options.attributeNamePrefix) && name !== this.options.textNodeName) {
    return name.substr(this.attrPrefixLen);
  } else {
    return false;
  }
}