Socket
Socket
Sign inDemoInstall

xml-formatter

Package Overview
Dependencies
Maintainers
1
Versions
39
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

xml-formatter - npm Package Compare versions

Comparing version 3.1.0 to 3.2.0

113

dist/browser/xml-formatter-singleton.js
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.xmlFormatter = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
"use strict";
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }
function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ParsingError = void 0;
var ParsingError = /*#__PURE__*/function (_Error) {
_inherits(ParsingError, _Error);
var _super = _createSuper(ParsingError);
function ParsingError(message, cause) {
var _this;
_classCallCheck(this, ParsingError);
_this = _super.call(this, message);
_this.cause = cause;
return _this;
}
return ParsingError;
}( /*#__PURE__*/_wrapNativeSuper(Error));
exports.ParsingError = ParsingError;
var parsingState;

@@ -41,5 +86,9 @@

if (!documentRootNode) {
throw new Error('Failed to parse XML');
throw new ParsingError('Failed to parse XML', 'Root Element not found');
}
if (parsingState.xml.length !== 0) {
throw new ParsingError('Failed to parse XML', 'Not Well-Formed XML');
}
return {

@@ -110,19 +159,16 @@ declaration: declaration ? declaration.node : null,

match(/\??>/);
match(/\??>/); // children
if (!excluded) {
// children
var child = nextChild();
var child = nextChild();
while (child) {
if (!child.excluded) {
node.children.push(child.node);
}
while (child) {
if (!child.excluded) {
node.children.push(child.node);
}
child = nextChild();
}
child = nextChild();
} // closing
match(/^<\/[\w-:.]+>/);
match(/^<\/\s*[\w-:.\u00C0-\u00FF]+>/);
return {

@@ -263,2 +309,3 @@ excluded: excluded,

module.exports = parseXml;
exports["default"] = parseXml;

@@ -412,20 +459,30 @@

options.lineSeparator = 'lineSeparator' in options ? options.lineSeparator : '\r\n';
options.whiteSpaceAtEndOfSelfclosingTag = !!options.whiteSpaceAtEndOfSelfclosingTag;
var parsedXml = (0, xml_parser_xo_1["default"])(xml, {
filter: options.filter
});
var state = {
content: '',
level: 0,
options: options
};
options.whiteSpaceAtEndOfSelfclosingTag = options.whiteSpaceAtEndOfSelfclosingTag === true;
options.throwOnFailure = options.throwOnFailure !== false;
if (parsedXml.declaration) {
processProcessingIntruction(parsedXml.declaration, state);
try {
var parsedXml = (0, xml_parser_xo_1["default"])(xml, {
filter: options.filter
});
var state = {
content: '',
level: 0,
options: options
};
if (parsedXml.declaration) {
processProcessingIntruction(parsedXml.declaration, state);
}
parsedXml.children.forEach(function (child) {
processNode(child, state, false);
});
return state.content.replace(/\r\n/g, '\n').replace(/\n/g, options.lineSeparator);
} catch (err) {
if (options.throwOnFailure) {
throw err;
}
return xml;
}
parsedXml.children.forEach(function (child) {
processNode(child, state, false);
});
return state.content.replace(/\r\n/g, '\n').replace(/\n/g, options.lineSeparator);
}

@@ -432,0 +489,0 @@

require=(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
"use strict";
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }
function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ParsingError = void 0;
var ParsingError = /*#__PURE__*/function (_Error) {
_inherits(ParsingError, _Error);
var _super = _createSuper(ParsingError);
function ParsingError(message, cause) {
var _this;
_classCallCheck(this, ParsingError);
_this = _super.call(this, message);
_this.cause = cause;
return _this;
}
return ParsingError;
}( /*#__PURE__*/_wrapNativeSuper(Error));
exports.ParsingError = ParsingError;
var parsingState;

@@ -41,5 +86,9 @@

if (!documentRootNode) {
throw new Error('Failed to parse XML');
throw new ParsingError('Failed to parse XML', 'Root Element not found');
}
if (parsingState.xml.length !== 0) {
throw new ParsingError('Failed to parse XML', 'Not Well-Formed XML');
}
return {

@@ -110,19 +159,16 @@ declaration: declaration ? declaration.node : null,

match(/\??>/);
match(/\??>/); // children
if (!excluded) {
// children
var child = nextChild();
var child = nextChild();
while (child) {
if (!child.excluded) {
node.children.push(child.node);
}
while (child) {
if (!child.excluded) {
node.children.push(child.node);
}
child = nextChild();
}
child = nextChild();
} // closing
match(/^<\/[\w-:.]+>/);
match(/^<\/\s*[\w-:.\u00C0-\u00FF]+>/);
return {

@@ -263,2 +309,3 @@ excluded: excluded,

module.exports = parseXml;
exports["default"] = parseXml;

@@ -412,20 +459,30 @@

options.lineSeparator = 'lineSeparator' in options ? options.lineSeparator : '\r\n';
options.whiteSpaceAtEndOfSelfclosingTag = !!options.whiteSpaceAtEndOfSelfclosingTag;
var parsedXml = (0, xml_parser_xo_1["default"])(xml, {
filter: options.filter
});
var state = {
content: '',
level: 0,
options: options
};
options.whiteSpaceAtEndOfSelfclosingTag = options.whiteSpaceAtEndOfSelfclosingTag === true;
options.throwOnFailure = options.throwOnFailure !== false;
if (parsedXml.declaration) {
processProcessingIntruction(parsedXml.declaration, state);
try {
var parsedXml = (0, xml_parser_xo_1["default"])(xml, {
filter: options.filter
});
var state = {
content: '',
level: 0,
options: options
};
if (parsedXml.declaration) {
processProcessingIntruction(parsedXml.declaration, state);
}
parsedXml.children.forEach(function (child) {
processNode(child, state, false);
});
return state.content.replace(/\r\n/g, '\n').replace(/\n/g, options.lineSeparator);
} catch (err) {
if (options.throwOnFailure) {
throw err;
}
return xml;
}
parsedXml.children.forEach(function (child) {
processNode(child, state, false);
});
return state.content.replace(/\r\n/g, '\n').replace(/\n/g, options.lineSeparator);
}

@@ -432,0 +489,0 @@

@@ -0,1 +1,2 @@

import { XmlParserNode } from 'xml-parser-xo';
export declare type XMLFormatterOptions = {

@@ -9,21 +10,26 @@ /**

* Return false to exclude the node.
* @param node
*/
filter?: (node: any) => boolean;
filter?: (node: XmlParserNode) => boolean;
/**
* True to remove comments
* True to keep content in the same line as the element.
* Notes: Only works if element contains at least one text node.
* Default: false
*/
stripComments?: boolean;
/**
* True to keep content in the same line as the element. Only works if element contains at least one text node
*/
collapseContent?: boolean;
/**
* The line separator to use
* The line separator to use.
* Default: '\r\n'
*/
lineSeparator?: string;
/**
* To either end ad self closing tag with `<tag/>` or `<tag />`
* To either end ad self closing tag with `<tag/>` or `<tag />`.
* Default: false
*/
whiteSpaceAtEndOfSelfclosingTag?: boolean;
/**
* Throw an error when XML fails to parse and get formatted.
* Notes: If set to `false`, the original XML is returned when an error occurs.
* Default: true
*/
throwOnFailure?: boolean;
};

@@ -30,0 +36,0 @@ /**

@@ -121,16 +121,25 @@ import xmlParser from 'xml-parser-xo';

options.lineSeparator = 'lineSeparator' in options ? options.lineSeparator : '\r\n';
options.whiteSpaceAtEndOfSelfclosingTag = !!options.whiteSpaceAtEndOfSelfclosingTag;
const parsedXml = xmlParser(xml, { filter: options.filter });
const state = { content: '', level: 0, options: options };
if (parsedXml.declaration) {
processProcessingIntruction(parsedXml.declaration, state);
options.whiteSpaceAtEndOfSelfclosingTag = options.whiteSpaceAtEndOfSelfclosingTag === true;
options.throwOnFailure = options.throwOnFailure !== false;
try {
const parsedXml = xmlParser(xml, { filter: options.filter });
const state = { content: '', level: 0, options: options };
if (parsedXml.declaration) {
processProcessingIntruction(parsedXml.declaration, state);
}
parsedXml.children.forEach(function (child) {
processNode(child, state, false);
});
return state.content
.replace(/\r\n/g, '\n')
.replace(/\n/g, options.lineSeparator);
}
parsedXml.children.forEach(function (child) {
processNode(child, state, false);
});
return state.content
.replace(/\r\n/g, '\n')
.replace(/\n/g, options.lineSeparator);
catch (err) {
if (options.throwOnFailure) {
throw err;
}
return xml;
}
}
module.exports = format;
export default format;

@@ -0,1 +1,2 @@

import { XmlParserNode } from 'xml-parser-xo';
export declare type XMLFormatterOptions = {

@@ -9,21 +10,26 @@ /**

* Return false to exclude the node.
* @param node
*/
filter?: (node: any) => boolean;
filter?: (node: XmlParserNode) => boolean;
/**
* True to remove comments
* True to keep content in the same line as the element.
* Notes: Only works if element contains at least one text node.
* Default: false
*/
stripComments?: boolean;
/**
* True to keep content in the same line as the element. Only works if element contains at least one text node
*/
collapseContent?: boolean;
/**
* The line separator to use
* The line separator to use.
* Default: '\r\n'
*/
lineSeparator?: string;
/**
* To either end ad self closing tag with `<tag/>` or `<tag />`
* To either end ad self closing tag with `<tag/>` or `<tag />`.
* Default: false
*/
whiteSpaceAtEndOfSelfclosingTag?: boolean;
/**
* Throw an error when XML fails to parse and get formatted.
* Notes: If set to `false`, the original XML is returned when an error occurs.
* Default: true
*/
throwOnFailure?: boolean;
};

@@ -30,0 +36,0 @@ /**

@@ -126,16 +126,25 @@ "use strict";

options.lineSeparator = 'lineSeparator' in options ? options.lineSeparator : '\r\n';
options.whiteSpaceAtEndOfSelfclosingTag = !!options.whiteSpaceAtEndOfSelfclosingTag;
const parsedXml = (0, xml_parser_xo_1.default)(xml, { filter: options.filter });
const state = { content: '', level: 0, options: options };
if (parsedXml.declaration) {
processProcessingIntruction(parsedXml.declaration, state);
options.whiteSpaceAtEndOfSelfclosingTag = options.whiteSpaceAtEndOfSelfclosingTag === true;
options.throwOnFailure = options.throwOnFailure !== false;
try {
const parsedXml = (0, xml_parser_xo_1.default)(xml, { filter: options.filter });
const state = { content: '', level: 0, options: options };
if (parsedXml.declaration) {
processProcessingIntruction(parsedXml.declaration, state);
}
parsedXml.children.forEach(function (child) {
processNode(child, state, false);
});
return state.content
.replace(/\r\n/g, '\n')
.replace(/\n/g, options.lineSeparator);
}
parsedXml.children.forEach(function (child) {
processNode(child, state, false);
});
return state.content
.replace(/\r\n/g, '\n')
.replace(/\n/g, options.lineSeparator);
catch (err) {
if (options.throwOnFailure) {
throw err;
}
return xml;
}
}
module.exports = format;
exports.default = format;
{
"name": "xml-formatter",
"version": "3.1.0",
"version": "3.2.0",
"repository": "github:chrisbottin/xml-formatter",

@@ -40,3 +40,3 @@ "bugs": {

"dependencies": {
"xml-parser-xo": "^4.0.0"
"xml-parser-xo": "^4.0.1"
},

@@ -43,0 +43,0 @@ "devDependencies": {

# xml-formatter
Converts XML into a human readable format (pretty print) while respecting the xml:space attribute.
Converts XML into a human readable format (pretty print) while respecting the `xml:space` attribute.

@@ -18,13 +18,11 @@ This module can also be used on the browser using the browserified version with a small footprint (8KB file size).

JavaScript:
### Usage:
```js
var format = require('xml-formatter');
var xml = '<root><content><p xml:space="preserve">This is <b>some</b> content.</content></p>';
import xmlFormat from 'xml-formatter';
var formattedXml = format(xml);
console.log(formattedXml);
xmlFormat('<root><content><p xml:space="preserve">This is <b>some</b> content.</content></p>');
```
Output:
### Output:

@@ -41,9 +39,15 @@ ```xml

JavaScript:
- `filter` (`function(node) => boolean`) Function to filter out unwanted nodes by returning `false`.
- `indentation` (String, default=`' '`) The value used for indentation.
- `collapseContent` (Boolean, default=`false`) True to keep content in the same line as the element. Only works if element contains at least one text node
- `lineSeparator` (String, default=`\r\n`) Specify the line separator to use
- `whiteSpaceAtEndOfSelfclosingTag` (Boolean, default=`false`) to either end ad self closing tag with `<tag/>` or `<tag />`
- `throwOnFailure` (Boolean, default=`true`) Throw an error when XML fails to parse and get formatted otherwise the original XML is returned
### Usage:
```js
var format = require('xml-formatter');
var xml = '<root><!-- content --><content><p>This is <b>some</b> content.</content></p>';
import xmlFormat from 'xml-formatter';
var formattedXml = format(xml, {
xmlFormat('<root><!-- content --><content><p>This is <b>some</b> content.</content></p>', {
indentation: ' ',

@@ -55,6 +59,5 @@ filter: (node) => node.type !== 'Comment',

console.log(formattedXml);
```
Output:
### Output:

@@ -69,9 +72,2 @@ ```xml

- `filter` (function(node)) Function to filter out unwanted nodes by returning false.
- `indentation` (String, default=`' '`) The value used for indentation.
- `collapseContent` (Boolean, default=`false`] True to keep content in the same line as the element. Only works if element contains at least one text node
- `lineSeparator` (String, default=`\r\n`) Specify the line separator to use
- `whiteSpaceAtEndOfSelfclosingTag` (Boolean, default=false) to either end ad self closing tag with `<tag/>` or `<tag />`
## On The Browser

@@ -82,3 +78,4 @@

### Using `require('xml-formatter')`
Page:
### Page:

@@ -89,10 +86,8 @@ ```html

Usage:
### Usage:
```js
var xmlFormatter = require('xml-formatter');
var xml = '<root><content><p xml:space="preserve">This is <b>some</b> content.</content></p>';
const xmlFormatter = require('xml-formatter');
var formattedXml = xmlFormatter(xml);
console.log(formattedXml);
xmlFormat('<root><content><p xml:space="preserve">This is <b>some</b> content.</content></p>');
```

@@ -102,2 +97,4 @@

### Page:
```html

@@ -107,9 +104,6 @@ <script type="text/javascript" src="dist/browser/xml-formatter-singleton.js"></script>

Usage:
### Usage:
```js
var xml = '<root><content><p xml:space="preserve">This is <b>some</b> content.</content></p>';
var formattedXml = xmlFormatter(xml);
console.log(formattedXml);
xmlFormatter('<root><content><p xml:space="preserve">This is <b>some</b> content.</content></p>');
```

@@ -127,4 +121,4 @@

# License
## License
MIT
MIT
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc