Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

xmlbuilder2

Package Overview
Dependencies
Maintainers
1
Versions
46
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

xmlbuilder2 - npm Package Compare versions

Comparing version 2.2.0 to 2.3.0

lib/readers/BaseReader.d.ts

8

CHANGELOG.md

@@ -5,2 +5,10 @@ # Change Log

## [2.3.0] - 2020-08-04
### Bug Fixes
- Fixed a bug where JSON serializer would not escape special characters (see [#44](https://github.com/oozcitak/xmlbuilder2/issues/44)).
### Features
- Added custom parsers (see [#25](https://github.com/oozcitak/xmlbuilder2/issues/25)).
- Added YAML parser and serializer.
## [2.2.0] - 2020-07-14

@@ -7,0 +15,0 @@

24

lib/builder/BuilderFunctions.d.ts

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

import { XMLBuilderCreateOptions, ExpandObject, XMLBuilder, XMLWriterOptions, JSONWriterOptions, ObjectWriterOptions, XMLSerializedAsObject, XMLSerializedAsObjectArray, MapWriterOptions, XMLSerializedAsMap, XMLSerializedAsMapArray } from '../interfaces';
import { XMLBuilderCreateOptions, ExpandObject, XMLBuilder, XMLWriterOptions, JSONWriterOptions, ObjectWriterOptions, XMLSerializedAsObject, XMLSerializedAsObjectArray, MapWriterOptions, XMLSerializedAsMap, XMLSerializedAsMapArray, YAMLWriterOptions } from '../interfaces';
import { Node } from '@oozcitak/dom/lib/dom/interfaces';

@@ -146,2 +146,12 @@ /**

/**
* Parses an XML document with the default options and converts it a YAML string.
*
* @param contents - a string containing an XML document in either XML or JSON
* format or a JS object representing nodes to insert
* @param convertOptions - convert options
*
* @returns document node
*/
export declare function convert(contents: string | ExpandObject, convertOptions: YAMLWriterOptions): string;
/**
* Parses an XML document with the default options and converts it to its object

@@ -193,2 +203,14 @@ * representation.

/**
* Parses an XML document with the given options and converts it to a YAML
* string.
*
* @param builderOptions - builder options
* @param contents - a string containing an XML document in either XML or JSON
* format or a JS object representing nodes to insert
* @param convertOptions - convert options
*
* @returns document node
*/
export declare function convert(builderOptions: XMLBuilderCreateOptions, contents: string | ExpandObject, convertOptions: YAMLWriterOptions): string;
/**
* Parses an XML document with the given options and converts it to its object

@@ -195,0 +217,0 @@ * representation.

98

lib/builder/BuilderFunctions.js
"use strict";
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
Object.defineProperty(exports, "__esModule", { value: true });

@@ -47,32 +36,9 @@ var interfaces_1 = require("../interfaces");

var contents = isXMLBuilderCreateOptions(p1) ? p2 : p1;
var builder;
if (contents === undefined) {
// empty document
var doc = dom_1.createDocument();
builder = new _1.XMLBuilderImpl(doc);
setOptions(doc, options);
}
else if (util_1.isObject(contents)) {
// JS object
var doc = dom_1.createDocument();
builder = new _1.XMLBuilderImpl(doc);
setOptions(doc, options);
var doc = dom_1.createDocument();
setOptions(doc, options);
var builder = new _1.XMLBuilderImpl(doc);
if (contents !== undefined) {
// parse contents
builder.ele(contents);
}
else if (/^\s*</.test(contents)) {
// XML document
var domParser = dom_1.createParser();
var doc = domParser.parseFromString(dom_1.sanitizeInput(contents, options.invalidCharReplacement), "text/xml");
dom_1.throwIfParserError(doc);
builder = new _1.XMLBuilderImpl(doc);
setOptions(doc, options);
}
else {
// JSON
var doc = dom_1.createDocument();
builder = new _1.XMLBuilderImpl(doc);
setOptions(doc, options);
var obj = JSON.parse(contents);
builder.ele(obj);
}
return builder;

@@ -83,56 +49,12 @@ }

function fragment(p1, p2) {
var e_1, _a;
var options = formatBuilderOptions(p1 === undefined || isXMLBuilderCreateOptions(p1) ?
p1 : interfaces_1.DefaultBuilderOptions);
var contents = isXMLBuilderCreateOptions(p1) ? p2 : p1;
var builder;
if (contents === undefined) {
// empty fragment
var doc = dom_1.createDocument();
setOptions(doc, options, true);
builder = new _1.XMLBuilderImpl(doc.createDocumentFragment());
}
else if (util_1.isObject(contents)) {
// JS object
var doc = dom_1.createDocument();
setOptions(doc, options, true);
builder = new _1.XMLBuilderImpl(doc.createDocumentFragment());
var doc = dom_1.createDocument();
setOptions(doc, options, true);
var builder = new _1.XMLBuilderImpl(doc.createDocumentFragment());
if (contents !== undefined) {
// parse contents
builder.ele(contents);
}
else if (/^\s*</.test(contents)) {
// XML document
var domParser = dom_1.createParser();
var doc = domParser.parseFromString("<TEMP_ROOT>" +
dom_1.sanitizeInput(contents, options.invalidCharReplacement) + "</TEMP_ROOT>", "text/xml");
dom_1.throwIfParserError(doc);
setOptions(doc, options, true);
/* istanbul ignore next */
if (doc.documentElement === null) {
throw new Error("Document element is null.");
}
var frag = doc.createDocumentFragment();
try {
for (var _b = __values(doc.documentElement.childNodes), _c = _b.next(); !_c.done; _c = _b.next()) {
var child = _c.value;
var newChild = doc.importNode(child, true);
frag.appendChild(newChild);
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_1) throw e_1.error; }
}
builder = new _1.XMLBuilderImpl(frag);
}
else {
// JSON
var doc = dom_1.createDocument();
setOptions(doc, options, true);
builder = new _1.XMLBuilderImpl(doc.createDocumentFragment());
var obj = JSON.parse(contents);
builder.ele(obj);
}
return builder;

@@ -139,0 +61,0 @@ }

import { Document } from "@oozcitak/dom/lib/dom/interfaces";
import { DOMParser } from "@oozcitak/dom";
/**
* Throws an error if the parser returned an error document.
*/
export declare function throwIfParserError(doc: Document): void;
/**
* Creates an XML document without any child nodes.
*/
export declare function createDocument(): Document;
/**
* Creates a DOM parser.
*/
export declare function createParser(): DOMParser;
export declare function sanitizeInput(str: string, replacement?: string | ((char: string, offset: number, str: string) => string)): string;
export declare function sanitizeInput(str: string | null, replacement?: string | ((char: string, offset: number, str: string) => string)): string | null;
export declare function sanitizeInput(str: string | null | undefined, replacement?: string | ((char: string, offset: number, str: string) => string)): string | null | undefined;

@@ -8,22 +8,2 @@ "use strict";

/**
* Throws an error if the parser returned an error document.
*/
function throwIfParserError(doc) {
var root = doc.documentElement;
if (root !== null &&
root.localName === "parsererror" &&
root.namespaceURI === "http://www.mozilla.org/newlayout/xml/parsererror.xml") {
var msgElement = root.firstElementChild;
/* istanbul ignore next */
if (msgElement === null)
throw new Error("Error parsing XML string.");
var msg = msgElement.getAttribute("message");
/* istanbul ignore next */
if (msg === null)
throw new Error("Error parsing XML string.");
throw new Error(msg);
}
}
exports.throwIfParserError = throwIfParserError;
/**
* Creates an XML document without any child nodes.

@@ -42,9 +22,2 @@ */

/**
* Creates a DOM parser.
*/
function createParser() {
return new dom_1.DOMParser();
}
exports.createParser = createParser;
/**
* Sanitizes input strings with user supplied replacement characters.

@@ -51,0 +24,0 @@ *

@@ -53,2 +53,3 @@ "use strict";

var JSONCBWriter_1 = require("../writers/JSONCBWriter");
var YAMLCBWriter_1 = require("../writers/YAMLCBWriter");
var events_1 = require("events");

@@ -84,3 +85,11 @@ /**

};
_this._writer = _this._options.format === "xml" ? new XMLCBWriter_1.XMLCBWriter(_this._options) : new JSONCBWriter_1.JSONCBWriter(_this._options);
if (_this._options.format === "json") {
_this._writer = new JSONCBWriter_1.JSONCBWriter(_this._options);
}
else if (_this._options.format === "yaml") {
_this._writer = new YAMLCBWriter_1.YAMLCBWriter(_this._options);
}
else {
_this._writer = new XMLCBWriter_1.XMLCBWriter(_this._options);
}
// automatically create listeners for callbacks passed via options

@@ -99,2 +108,3 @@ if (_this._options.data !== undefined) {

_this._prefixIndex = { value: 1 };
_this._push(_this._writer.frontMatter());
return _this;

@@ -101,0 +111,0 @@ }

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

import { XMLBuilderOptions, XMLBuilder, AttributesObject, ExpandObject, WriterOptions, DTDOptions, PIObject, XMLWriterOptions, JSONWriterOptions, ObjectWriterOptions, MapWriterOptions } from "../interfaces";
import { XMLBuilderOptions, XMLBuilder, AttributesObject, ExpandObject, WriterOptions, DTDOptions, PIObject, XMLWriterOptions, JSONWriterOptions, ObjectWriterOptions, MapWriterOptions, YAMLWriterOptions } from "../interfaces";
import { Document, Node } from "@oozcitak/dom/lib/dom/interfaces";

@@ -78,3 +78,3 @@ /**

/** @inheritdoc */
toString(writerOptions?: XMLWriterOptions | JSONWriterOptions): string;
toString(writerOptions?: XMLWriterOptions | JSONWriterOptions | YAMLWriterOptions): string;
/** @inheritdoc */

@@ -119,3 +119,3 @@ toObject(writerOptions?: ObjectWriterOptions | MapWriterOptions): any;

* @param name - a string containing both a name and namespace separated by an
* '@' character
* `'@'` character
* @param ele - `true` if this is an element namespace; otherwise `false`

@@ -122,0 +122,0 @@ */

@@ -76,22 +76,17 @@ "use strict";

var attributes;
var lastChild = null;
if (p1 !== null && util_1.isFunction(p2)) {
// parse with custom parser function
lastChild = p2.call(this, p1);
if (lastChild === null) {
throw new Error("Could not create any elements with: " + p1.toString() + ". " + this._debugInfo());
}
return lastChild;
if (util_1.isObject(p1)) {
// ele(obj: ExpandObject)
return new readers_1.ObjectReader(this._options).parse(this, p1);
}
else if (util_1.isString(p1) && /^\s*</.test(p1)) {
else if (p1 !== null && /^\s*</.test(p1)) {
// parse XML document string
return new readers_1.XMLReader().parse(this, p1);
return new readers_1.XMLReader(this._options).parse(this, p1);
}
else if (util_1.isString(p1) && /^\s*[\{\[]/.test(p1)) {
else if (p1 !== null && /^\s*[\{\[]/.test(p1)) {
// parse JSON string
return new readers_1.JSONReader().parse(this, p1);
return new readers_1.JSONReader(this._options).parse(this, p1);
}
else if (util_1.isObject(p1)) {
// ele(obj: ExpandObject)
return new readers_1.ObjectReader().parse(this, p1);
else if (p1 !== null && /^(\s*|(#.*)|(%.*))*---/.test(p1)) {
// parse YAML string
return new readers_1.YAMLReader(this._options).parse(this, p1);
}

@@ -123,3 +118,3 @@ if ((p1 === null || util_1.isString(p1)) && util_1.isString(p2)) {

this.node.appendChild(childNode);
lastChild = new XMLBuilderImpl(childNode);
var builder = new XMLBuilderImpl(childNode);
// update doctype node if the new node is the document element node

@@ -133,8 +128,5 @@ var oldDocType = this._doc.doctype;

if (attributes && !util_1.isEmpty(attributes)) {
lastChild.att(attributes);
builder.att(attributes);
}
if (lastChild === null) {
throw new Error("Could not create any elements with: " + name.toString() + ". " + this._debugInfo());
}
return lastChild;
return builder;
};

@@ -648,2 +640,6 @@ /** @inheritdoc */

}
else if (writerOptions.format === "yaml") {
var writer = new writers_1.YAMLWriter(this._options);
return writer.serialize(this.node, writerOptions);
}
else {

@@ -658,3 +654,3 @@ throw new Error("Invalid writer format: " + writerOptions.format + ". " + this._debugInfo());

* @param name - a string containing both a name and namespace separated by an
* '@' character
* `'@'` character
* @param ele - `true` if this is an element namespace; otherwise `false`

@@ -661,0 +657,0 @@ */

@@ -96,2 +96,6 @@ import { Node, Document } from "@oozcitak/dom/lib/dom/interfaces";

invalidCharReplacement: string | ((char: string, offset: number, str: string) => string) | undefined;
/**
* Defines custom parser functions.
*/
parser: ParserOptions | undefined;
}

@@ -243,2 +247,92 @@ /**

/**
* Defines custom parser functions.
*/
export declare type ParserOptions = {
/**
* Main parser function which parses the given object and returns an `XMLBuilder`.
*
* @param node - node to recieve parsed content
* @param obj - object to parse
*
* @returns the last top level element node created
*/
parse?: (parent: XMLBuilder, obj: string | ExpandObject) => XMLBuilder;
/**
* Creates a DocType node.
* The node will be skipped if the function returns `undefined`.
*
* @param parent - parent node
* @param name - node name
* @param publicId - public identifier
* @param systemId - system identifier
*
* @returns the parent document node
*/
docType?: (parent: XMLBuilder, name: string, publicId: string, systemId: string) => XMLBuilder | undefined;
/**
* Creates a comment node.
* The node will be skipped if the function returns `undefined`.
*
* @param parent - parent node
* @param data - node data
*
* @returns the parent element node
*/
comment?: (parent: XMLBuilder, data: string) => XMLBuilder | undefined;
/**
* Creates a text node.
* The node will be skipped if the function returns `undefined`.
*
* @param parent - parent node
* @param data - node data
*
* @returns the parent element node
*/
text?: (parent: XMLBuilder, data: string) => XMLBuilder | undefined;
/**
* Creates a processing instruction node.
* The node will be skipped if the function returns `undefined`.
*
* @param parent - parent node
* @param target - instruction target
* @param data - node data
*
* @returns the parent element node
*/
instruction?: (parent: XMLBuilder, target: string, data: string) => XMLBuilder | undefined;
/**
* Creates a CData section node.
* The node will be skipped if the function returns `undefined`.
*
* @param parent - parent node
* @param data - node data
*
* @returns the parent element node
*/
cdata?: (parent: XMLBuilder, data: string) => XMLBuilder | undefined;
/**
* Creates an element node.
* The node will be skipped if the function returns `undefined`.
*
* @param parent - parent node
* @param namespace - element namespace
* @param name - node name
*
* @returns the new element node
*/
element?: (parent: XMLBuilder, namespace: string | null | undefined, name: string) => XMLBuilder | undefined;
/**
* Creates an attribute or namespace declaration.
* The node will be skipped if the function returns `undefined`.
*
* @param parent - parent node
* @param namespace - attribute namespace
* @param name - attribute name
* @param value - attribute value
*
* @returns the parent element node
*/
attribute?: (parent: XMLBuilder, namespace: string | null | undefined, name: string, value: string) => XMLBuilder | undefined;
};
/**
* Defines the options passed to the writer.

@@ -255,4 +349,5 @@ */

* - `"json"` - Serializes the document as a JSON string.
* - `"yaml"` - Serilizes the document as a YAML string
*/
format?: "xml" | "map" | "object" | "json";
format?: "xml" | "map" | "object" | "json" | "yaml";
/**

@@ -411,5 +506,35 @@ * Ensures that the document adheres to the syntax rules specified by the

/**
* Defines the options passed to the YAML writer.
*/
export declare type YAMLWriterOptions = BaseWriterOptions & {
/** @inheritdoc */
format?: "yaml";
/**
* Determines the indentation string. Defaults to two space characters.
*/
indent?: string;
/**
* Determines the newline string. Defaults to `"\n"`.
*/
newline?: string;
/**
* Defines a fixed number of indentations to add to every line. Defaults to
* `0`.
*/
offset?: number;
/**
* Groups consecutive nodes of same type under a single object. Defaults to
* `false`.
*/
group?: boolean;
/**
* Outputs child nodes as an array, even if the parent node has only one
* child node.
*/
verbose?: boolean;
};
/**
* Defines the options passed to the writer.
*/
export declare type WriterOptions = XMLWriterOptions | ObjectWriterOptions | JSONWriterOptions | MapWriterOptions;
export declare type WriterOptions = XMLWriterOptions | ObjectWriterOptions | JSONWriterOptions | MapWriterOptions | YAMLWriterOptions;
/**

@@ -503,10 +628,10 @@ * Defines recursive types that can represent objects, arrays and maps of

/**
* Creates new element nodes from the given JS object and appends it to the
* list of child nodes.
*
* @param obj - a JS object representing nodes to insert
*
* @returns the last top level element node created
*/
ele(obj: ExpandObject, parser: ((obj: ExpandObject) => XMLBuilder)): XMLBuilder;
* Creates new element nodes from the given XML document string appends it to the
* list of child nodes.
*
* @param content - an XML document string representing nodes to insert
*
* @returns the last top level element node created
*/
ele(content: string): XMLBuilder;
/**

@@ -790,2 +915,8 @@ * Removes this node from the XML document.

/**
* Converts the node into a YAML string.
*
* @param options - serialization options
*/
toString(writerOptions: YAMLWriterOptions): string;
/**
* Converts the node into its object representation.

@@ -820,2 +951,8 @@ *

/**
* Converts the entire XML document into a YAML string.
*
* @param options - serialization options
*/
end(writerOptions: YAMLWriterOptions): string;
/**
* Converts the entire XML document into its object representation.

@@ -1081,4 +1218,5 @@ *

* - `"json"` - Serializes the document as a JSON string.
* - `"yaml"` - Serializes the document as a YAML string.
*/
format?: "xml" | "json";
format?: "xml" | "json" | "yaml";
/**

@@ -1173,5 +1311,25 @@ * Ensures that the document adheres to the syntax rules specified by the

/**
* Defines the options passed to the the callback builder's YAML writer.
*/
export declare type YAMLCBWriterOptions = BaseCBWriterOptions & {
/** @inheritdoc */
format?: "yaml";
/**
* Determines the indentation string. Defaults to two space characters.
*/
indent: string;
/**
* Determines the newline string. Defaults to `"\n"`.
*/
newline: string;
/**
* Defines a fixed number of indentations to add to every line. Defaults to
* `0`.
*/
offset: number;
};
/**
* Defines the options passed to the callback builder's writer.
*/
export declare type CBWriterOptions = XMLCBWriterOptions | JSONCBWriterOptions;
export declare type CBWriterOptions = XMLCBWriterOptions | JSONCBWriterOptions | YAMLCBWriterOptions;
/**

@@ -1178,0 +1336,0 @@ * Defines the options passed to the callback builder.

@@ -32,3 +32,4 @@ "use strict";

},
invalidCharReplacement: undefined
invalidCharReplacement: undefined,
parser: undefined
};

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

export { XMLReader } from './XMLReader';
export { ObjectReader } from './ObjectReader';
export { JSONReader } from './JSONReader';
export { YAMLReader } from './YAMLReader';

@@ -9,2 +9,4 @@ "use strict";

exports.JSONReader = JSONReader_1.JSONReader;
var YAMLReader_1 = require("./YAMLReader");
exports.YAMLReader = YAMLReader_1.YAMLReader;
//# sourceMappingURL=index.js.map
import { XMLBuilder } from "../interfaces";
import { BaseReader } from "./BaseReader";
/**
* Parses XML nodes from JSON string.
* Parses XML nodes from a JSON string.
*/
export declare class JSONReader {
export declare class JSONReader extends BaseReader<string> {
/**

@@ -12,3 +13,3 @@ * Parses the given document representation.

*/
parse(node: XMLBuilder, str: string): XMLBuilder;
_parse(node: XMLBuilder, str: string): XMLBuilder;
}
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var ObjectReader_1 = require("./ObjectReader");
var BaseReader_1 = require("./BaseReader");
/**
* Parses XML nodes from JSON string.
* Parses XML nodes from a JSON string.
*/
var JSONReader = /** @class */ (function () {
var JSONReader = /** @class */ (function (_super) {
__extends(JSONReader, _super);
function JSONReader() {
return _super !== null && _super.apply(this, arguments) || this;
}

@@ -16,8 +32,8 @@ /**

*/
JSONReader.prototype.parse = function (node, str) {
return new ObjectReader_1.ObjectReader().parse(node, JSON.parse(str));
JSONReader.prototype._parse = function (node, str) {
return new ObjectReader_1.ObjectReader(this._builderOptions).parse(node, JSON.parse(str));
};
return JSONReader;
}());
}(BaseReader_1.BaseReader));
exports.JSONReader = JSONReader;
//# sourceMappingURL=JSONReader.js.map
import { XMLBuilder, ExpandObject } from "../interfaces";
import { BaseReader } from "./BaseReader";
/**
* Parses XML nodes from objects and arrays.
* ES6 maps and sets are laso suupoted.
* ES6 maps and sets are also supoorted.
*/
export declare class ObjectReader {
export declare class ObjectReader extends BaseReader<ExpandObject> {
/** @inheritdoc */
docType(parent: XMLBuilder, name: string, publicId: string, systemId: string): XMLBuilder | undefined;
/**

@@ -13,14 +16,3 @@ * Parses the given document representation.

*/
parse(node: XMLBuilder, obj: ExpandObject): XMLBuilder;
/**
* Creates a dummy element node without adding it to the list of child nodes.
*
* Dummy nodes are special nodes representing a node with a `null` value.
* Dummy nodes are created while recursively building the XML tree. Simply
* skipping `null` values doesn't work because that would break the recursive
* chain.
*
* @returns the new dummy element node
*/
private _dummy;
_parse(node: XMLBuilder, obj: ExpandObject): XMLBuilder;
}
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var util_1 = require("@oozcitak/util");
var XMLBuilderImpl_1 = require("../builder/XMLBuilderImpl");
var BaseReader_1 = require("./BaseReader");
/**
* Parses XML nodes from objects and arrays.
* ES6 maps and sets are laso suupoted.
* ES6 maps and sets are also supoorted.
*/
var ObjectReader = /** @class */ (function () {
var ObjectReader = /** @class */ (function (_super) {
__extends(ObjectReader, _super);
function ObjectReader() {
return _super !== null && _super.apply(this, arguments) || this;
}
/** @inheritdoc */
ObjectReader.prototype.docType = function (parent, name, publicId, systemId) {
// document type nodes cannot be represented in a JS object
return undefined;
};
/**

@@ -18,12 +38,12 @@ * Parses the given document representation.

*/
ObjectReader.prototype.parse = function (node, obj) {
ObjectReader.prototype._parse = function (node, obj) {
var _this = this;
var options = node.options;
var options = this._builderOptions;
var lastChild = null;
if (util_1.isFunction(obj)) {
// evaluate if function
lastChild = node.ele(obj.apply(this));
lastChild = this.parse(node, obj.apply(this));
}
else if (util_1.isArray(obj) || util_1.isSet(obj)) {
util_1.forEachArray(obj, function (item) { return lastChild = node.ele(item); }, this);
util_1.forEachArray(obj, function (item) { return lastChild = _this.parse(node, item); }, this);
}

@@ -40,6 +60,13 @@ else /* if (isMap(obj) || isObject(obj)) */ {

if (key === options.convert.att) {
lastChild = node.att(val);
if (util_1.isArray(val) || util_1.isSet(val)) {
throw new Error("Invalid attribute: " + val.toString() + ". " + node._debugInfo());
}
else /* if (isMap(val) || isObject(val)) */ {
util_1.forEachObject(val, function (attrKey, attrVal) {
lastChild = _this.attribute(node, undefined, attrKey, attrVal) || lastChild;
});
}
}
else {
lastChild = node.att(key.substr(options.convert.att.length), val);
lastChild = _this.attribute(node, undefined, key.substr(options.convert.att.length), val) || lastChild;
}

@@ -51,6 +78,6 @@ }

// if the key is #text expand child nodes under this node to support mixed content
lastChild = node.ele(val);
lastChild = _this.parse(node, val);
}
else {
lastChild = node.txt(val);
lastChild = _this.text(node, val) || lastChild;
}

@@ -61,6 +88,6 @@ }

if (util_1.isArray(val) || util_1.isSet(val)) {
util_1.forEachArray(val, function (item) { return lastChild = node.dat(item); }, _this);
util_1.forEachArray(val, function (item) { return lastChild = _this.cdata(node, item) || lastChild; }, _this);
}
else {
lastChild = node.dat(val);
lastChild = _this.cdata(node, val) || lastChild;
}

@@ -71,6 +98,6 @@ }

if (util_1.isArray(val) || util_1.isSet(val)) {
util_1.forEachArray(val, function (item) { return lastChild = node.com(item); }, _this);
util_1.forEachArray(val, function (item) { return lastChild = _this.comment(node, item) || lastChild; }, _this);
}
else {
lastChild = node.com(val);
lastChild = _this.comment(node, val) || lastChild;
}

@@ -84,19 +111,25 @@ }

var insValue = (insIndex === -1 ? '' : val.substr(insIndex + 1));
lastChild = node.ins(insTarget, insValue);
lastChild = _this.instruction(node, insTarget, insValue) || lastChild;
}
else {
lastChild = node.ins(val);
else if (util_1.isArray(val) || util_1.isSet(val)) {
util_1.forEachArray(val, function (item) {
var insIndex = item.indexOf(' ');
var insTarget = (insIndex === -1 ? item : item.substr(0, insIndex));
var insValue = (insIndex === -1 ? '' : item.substr(insIndex + 1));
lastChild = _this.instruction(node, insTarget, insValue) || lastChild;
}, _this);
}
else /* if (isMap(target) || isObject(target)) */ {
util_1.forEachObject(val, function (insTarget, insValue) { return lastChild = _this.instruction(node, insTarget, insValue) || lastChild; }, _this);
}
}
else if ((util_1.isArray(val) || util_1.isSet(val)) && util_1.isEmpty(val)) {
// skip empty arrays
lastChild = _this._dummy(node);
}
else if ((util_1.isMap(val) || util_1.isObject(val)) && util_1.isEmpty(val)) {
// empty objects produce one node
lastChild = node.ele(key);
lastChild = _this.element(node, undefined, key) || lastChild;
}
else if (!options.keepNullNodes && (val == null)) {
// skip null and undefined nodes
lastChild = _this._dummy(node);
}

@@ -108,3 +141,3 @@ else if (util_1.isArray(val) || util_1.isSet(val)) {

childNode[key] = item;
lastChild = node.ele(childNode);
lastChild = _this.parse(node, childNode);
}, _this);

@@ -114,14 +147,20 @@ }

// create a parent node
lastChild = node.ele(key);
// expand child nodes under parent
lastChild.ele(val);
var parent = _this.element(node, undefined, key);
if (parent) {
lastChild = parent;
// expand child nodes under parent
_this.parse(parent, val);
}
}
else if (val != null && val !== '') {
// leaf element node with a single text node
lastChild = node.ele(key);
lastChild.txt(val);
var parent = _this.element(node, undefined, key);
if (parent) {
lastChild = parent;
_this.text(parent, val);
}
}
else {
// leaf element node
lastChild = node.ele(key);
lastChild = _this.element(node, undefined, key) || lastChild;
}

@@ -135,18 +174,5 @@ }, this);

};
/**
* Creates a dummy element node without adding it to the list of child nodes.
*
* Dummy nodes are special nodes representing a node with a `null` value.
* Dummy nodes are created while recursively building the XML tree. Simply
* skipping `null` values doesn't work because that would break the recursive
* chain.
*
* @returns the new dummy element node
*/
ObjectReader.prototype._dummy = function (node) {
return new XMLBuilderImpl_1.XMLBuilderImpl(node._doc.createElement('dummy_node'));
};
return ObjectReader;
}());
}(BaseReader_1.BaseReader));
exports.ObjectReader = ObjectReader;
//# sourceMappingURL=ObjectReader.js.map
import { XMLBuilder } from "../interfaces";
import { BaseReader } from "./BaseReader";
/**
* Parses XML nodes from JSON string.
* Parses XML nodes from an XML document string.
*/
export declare class XMLReader {
export declare class XMLReader extends BaseReader<string> {
/**

@@ -12,3 +13,3 @@ * Parses the given document representation.

*/
parse(node: XMLBuilder, str: string): XMLBuilder;
_parse(node: XMLBuilder, str: string): XMLBuilder;
}
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __values = (this && this.__values) || function(o) {

@@ -14,9 +43,15 @@ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;

Object.defineProperty(exports, "__esModule", { value: true });
var XMLStringLexer_1 = require("@oozcitak/dom/lib/parser/XMLStringLexer");
var interfaces_1 = require("@oozcitak/dom/lib/parser/interfaces");
var infra_1 = require("@oozcitak/infra");
var algorithm_1 = require("@oozcitak/dom/lib/algorithm");
var dom_1 = require("../builder/dom");
var XMLBuilderImpl_1 = require("../builder/XMLBuilderImpl");
var BaseReader_1 = require("./BaseReader");
/**
* Parses XML nodes from JSON string.
* Parses XML nodes from an XML document string.
*/
var XMLReader = /** @class */ (function () {
var XMLReader = /** @class */ (function (_super) {
__extends(XMLReader, _super);
function XMLReader() {
return _super !== null && _super.apply(this, arguments) || this;
}

@@ -29,39 +64,132 @@ /**

*/
XMLReader.prototype.parse = function (node, str) {
var e_1, _a;
var ele = node;
var options = node.options;
var lastChild = null;
// parse XML string
var contents = "<TEMP_ROOT>" + str + "</TEMP_ROOT>";
var domParser = dom_1.createParser();
var doc = domParser.parseFromString(dom_1.sanitizeInput(contents, options.invalidCharReplacement), "text/xml");
/* istanbul ignore next */
if (doc.documentElement === null) {
throw new Error("Document element is null.");
}
dom_1.throwIfParserError(doc);
try {
for (var _b = __values(doc.documentElement.childNodes), _c = _b.next(); !_c.done; _c = _b.next()) {
var child = _c.value;
var newChild = ele._doc.importNode(child, true);
lastChild = new XMLBuilderImpl_1.XMLBuilderImpl(newChild);
ele._domNode.appendChild(newChild);
XMLReader.prototype._parse = function (node, str) {
var e_1, _a, e_2, _b;
var lexer = new XMLStringLexer_1.XMLStringLexer(str, { skipWhitespaceOnlyText: true });
var context = node;
var token = lexer.nextToken();
while (token.type !== interfaces_1.TokenType.EOF) {
switch (token.type) {
case interfaces_1.TokenType.Declaration:
var declaration = token;
if (declaration.version !== "1.0") {
throw new Error("Invalid xml version: " + declaration.version);
}
break;
case interfaces_1.TokenType.DocType:
var doctype = token;
context = this.docType(context, doctype.name, doctype.pubId, doctype.sysId) || context;
break;
case interfaces_1.TokenType.CDATA:
var cdata = token;
context = this.cdata(context, cdata.data) || context;
break;
case interfaces_1.TokenType.Comment:
var comment = token;
context = this.comment(context, comment.data) || context;
break;
case interfaces_1.TokenType.PI:
var pi = token;
context = this.instruction(context, pi.target, pi.data) || context;
break;
case interfaces_1.TokenType.Text:
var text = token;
context = this.text(context, text.data) || context;
break;
case interfaces_1.TokenType.Element:
var element = token;
// inherit namespace from parent
var _c = __read(algorithm_1.namespace_extractQName(dom_1.sanitizeInput(element.name, this._builderOptions.invalidCharReplacement)), 1), prefix = _c[0];
var namespace = context.node.lookupNamespaceURI(prefix);
// override namespace if there is a namespace declaration
// attribute
// also lookup namespace declaration attributes
var nsDeclarations = {};
try {
for (var _d = (e_1 = void 0, __values(element.attributes)), _e = _d.next(); !_e.done; _e = _d.next()) {
var _f = __read(_e.value, 2), attName = _f[0], attValue = _f[1];
attName = dom_1.sanitizeInput(attName, this._builderOptions.invalidCharReplacement);
attValue = dom_1.sanitizeInput(attValue, this._builderOptions.invalidCharReplacement);
if (attName === "xmlns") {
namespace = attValue;
}
else {
var _g = __read(algorithm_1.namespace_extractQName(attName), 2), attPrefix = _g[0], attLocalName = _g[1];
if (attPrefix === "xmlns") {
if (attLocalName === prefix) {
namespace = attValue;
}
nsDeclarations[attLocalName] = attValue;
}
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
}
finally { if (e_1) throw e_1.error; }
}
// create the DOM element node
var elementNode = (namespace !== null ?
this.element(context, namespace, element.name) :
this.element(context, undefined, element.name));
if (elementNode === undefined)
break;
try {
// assign attributes
for (var _h = (e_2 = void 0, __values(element.attributes)), _j = _h.next(); !_j.done; _j = _h.next()) {
var _k = __read(_j.value, 2), attName = _k[0], attValue = _k[1];
attName = dom_1.sanitizeInput(attName, this._builderOptions.invalidCharReplacement);
attValue = dom_1.sanitizeInput(attValue, this._builderOptions.invalidCharReplacement);
var _l = __read(algorithm_1.namespace_extractQName(attName), 2), attPrefix = _l[0], attLocalName = _l[1];
var attNamespace = null;
if (attPrefix === "xmlns" || (attPrefix === null && attLocalName === "xmlns")) {
// namespace declaration attribute
attNamespace = infra_1.namespace.XMLNS;
}
else {
attNamespace = elementNode.node.lookupNamespaceURI(attPrefix);
if (attNamespace !== null && elementNode.node.isDefaultNamespace(attNamespace)) {
attNamespace = null;
}
else if (attNamespace === null && attPrefix !== null) {
attNamespace = nsDeclarations[attPrefix] || null;
}
}
if (attNamespace !== null)
this.attribute(elementNode, attNamespace, attName, attValue);
else
this.attribute(elementNode, undefined, attName, attValue);
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (_j && !_j.done && (_b = _h.return)) _b.call(_h);
}
finally { if (e_2) throw e_2.error; }
}
if (!element.selfClosing) {
context = elementNode;
}
break;
case interfaces_1.TokenType.ClosingTag:
var closingTag = token;
if (dom_1.sanitizeInput(closingTag.name, this._builderOptions.invalidCharReplacement) !== context.node.nodeName) {
throw new Error('Closing tag name does not match opening tag name.');
}
/* istanbul ignore else */
if (context.node.parentNode) {
context = context.up();
}
break;
}
token = lexer.nextToken();
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_1) throw e_1.error; }
}
if (lastChild === null) {
throw new Error("Could not create any elements with: " + str.toString() + ". " + ele._debugInfo());
}
return lastChild;
return context;
};
return XMLReader;
}());
}(BaseReader_1.BaseReader));
exports.XMLReader = XMLReader;
//# sourceMappingURL=XMLReader.js.map

@@ -23,2 +23,6 @@ import { XMLBuilderCBOptions, BaseCBWriterOptions } from "../interfaces";

/**
* Used by derived classes to serialize a front matter.
*/
abstract frontMatter(): string;
/**
* Used by derived classes to serialize the XML declaration.

@@ -25,0 +29,0 @@ *

@@ -5,1 +5,2 @@ export { MapWriter } from './MapWriter';

export { JSONWriter } from './JSONWriter';
export { YAMLWriter } from './YAMLWriter';

@@ -11,2 +11,4 @@ "use strict";

exports.JSONWriter = JSONWriter_1.JSONWriter;
var YAMLWriter_1 = require("./YAMLWriter");
exports.YAMLWriter = YAMLWriter_1.YAMLWriter;
//# sourceMappingURL=index.js.map

@@ -10,3 +10,3 @@ import { XMLBuilderCBOptions, JSONCBWriterOptions } from "../interfaces";

/**
* Initializes a new instance of `BaseCBWriter`.
* Initializes a new instance of `JSONCBWriter`.
*

@@ -17,2 +17,4 @@ * @param builderOptions - XML builder options

/** @inheritdoc */
frontMatter(): string;
/** @inheritdoc */
declaration(version: "1.0", encoding?: string, standalone?: boolean): string;

@@ -19,0 +21,0 @@ /** @inheritdoc */

@@ -23,3 +23,3 @@ "use strict";

/**
* Initializes a new instance of `BaseCBWriter`.
* Initializes a new instance of `JSONCBWriter`.
*

@@ -35,2 +35,6 @@ * @param builderOptions - XML builder options

/** @inheritdoc */
JSONCBWriter.prototype.frontMatter = function () {
return "";
};
/** @inheritdoc */
JSONCBWriter.prototype.declaration = function (version, encoding, standalone) {

@@ -165,3 +169,3 @@ return "";

JSONCBWriter.prototype._val = function (val) {
return "\"" + val + "\"";
return JSON.stringify(val);
};

@@ -168,0 +172,0 @@ return JSONCBWriter;

@@ -53,3 +53,4 @@ "use strict";

offset: 0,
group: false
group: false,
verbose: false
});

@@ -136,3 +137,3 @@ // convert to object

else {
markup += '"' + obj + '"';
markup += JSON.stringify(obj);
}

@@ -139,0 +140,0 @@ return markup;

@@ -9,3 +9,3 @@ import { XMLBuilderCBOptions, XMLCBWriterOptions } from "../interfaces";

/**
* Initializes a new instance of `BaseCBWriter`.
* Initializes a new instance of `XMLCBWriter`.
*

@@ -16,2 +16,4 @@ * @param builderOptions - XML builder options

/** @inheritdoc */
frontMatter(): string;
/** @inheritdoc */
declaration(version: "1.0", encoding?: string, standalone?: boolean): string;

@@ -18,0 +20,0 @@ /** @inheritdoc */

@@ -23,3 +23,3 @@ "use strict";

/**
* Initializes a new instance of `BaseCBWriter`.
* Initializes a new instance of `XMLCBWriter`.
*

@@ -34,2 +34,6 @@ * @param builderOptions - XML builder options

/** @inheritdoc */
XMLCBWriter.prototype.frontMatter = function () {
return "";
};
/** @inheritdoc */
XMLCBWriter.prototype.declaration = function (version, encoding, standalone) {

@@ -36,0 +40,0 @@ var markup = this._beginLine() + "<?xml";

{
"name": "xmlbuilder2",
"version": "2.2.0",
"version": "2.3.0",
"keywords": [

@@ -32,3 +32,4 @@ "xml",

"@oozcitak/dom": "1.15.8",
"@oozcitak/infra": "1.0.8"
"@oozcitak/infra": "1.0.8",
"js-yaml": "3.14.0"
},

@@ -43,2 +44,3 @@ "devDependencies": {

"@types/node": "*",
"@types/js-yaml": "3.11.1",
"babel-loader": "*",

@@ -45,0 +47,0 @@ "benchmark": "*",

@@ -166,3 +166,3 @@ # xmlbuilder2

You can build the minified production bundle (`lib\xmlbuilder2.min.js`) after cloning the repository and issuing `npx webpack` in your terminal. The bundle is also in the npm package, so you can also use a public npm CDN like [jsDelivr](https://www.jsdelivr.com/) or [unpkg](https://unpkg.com/):
You can build the minified production bundle (`lib/xmlbuilder2.min.js`) after cloning the repository and issuing `npx webpack` in your terminal. The bundle is also in the npm package, so you can also use a public npm CDN like [jsDelivr](https://www.jsdelivr.com/) or [unpkg](https://unpkg.com/):

@@ -169,0 +169,0 @@ ```html

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

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