video-ad-sdk
Version:
VAST/VPAID SDK that allows video ads to be played on top of any player
64 lines (63 loc) • 2.13 kB
JavaScript
import { NodeType } from '../../types';
const NODE_TYPE = {
1: NodeType.ELEMENT,
3: NodeType.TEXT,
4: NodeType.TEXT
};
const DOCUMENT_TYPE = {
9: NodeType.DOCUMENT
};
const getNodeType = (node) => {
var _a;
const nodeType = (_a = NODE_TYPE[node.nodeType]) !== null && _a !== void 0 ? _a : DOCUMENT_TYPE[node.nodeType];
if (!nodeType) {
throw new Error('Unsupported element type');
}
return nodeType;
};
const getNodeAttributes = (node) => node.attributes.length === 0
? undefined
: Object.fromEntries(Array.from(node.attributes).map((attribute) => {
var _a;
return [
attribute.nodeName,
(_a = attribute.nodeValue) !== null && _a !== void 0 ? _a : undefined
];
}));
const getNodeText = (node) => { var _a; return (_a = node.nodeValue) === null || _a === void 0 ? void 0 : _a.replace('<![CDATA[', '').replace(']]>', '').trim(); };
const getNodeChildren = (node) => {
var _a, _b;
if (!node.hasChildNodes()) {
return;
}
const childNodes = Array.from(node.childNodes).filter((childNode) => Object.keys(NODE_TYPE).map(Number).includes(childNode.nodeType));
const elements = [];
for (const childNode of childNodes) {
const childElement = xmlToJson(childNode);
if (!(childNode instanceof Text) || ((_b = (_a = childElement.text) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0) > 0) {
elements.push(childElement);
}
}
return elements;
};
export const xmlToJson = (node) => {
const type = getNodeType(node);
const element = {
type
};
if (node instanceof Element) {
const attributes = getNodeAttributes(node);
if (attributes) {
element.attributes = attributes;
}
element.name = node.nodeName.toLowerCase();
}
else if (node instanceof Text || node instanceof CDATASection) {
element.text = getNodeText(node);
}
const children = getNodeChildren(node);
if (children) {
element.elements = children;
}
return element;
};