UNPKG

@forzalabs/remora

Version:

A powerful CLI tool for seamless data translation.

60 lines (59 loc) 2.61 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const fast_xml_parser_1 = require("fast-xml-parser"); const Affirm_1 = __importDefault(require("../../core/Affirm")); const DEFAULT_OPTIONS = { attributeNamePrefix: '@_', ignoreAttributes: false, parseAttributeValue: true, parseTagValue: true, trimValues: true, isArray: () => { return false; } }; class XMLParserClass { constructor(options) { this.xmlToJson = (xmlData) => { (0, Affirm_1.default)(xmlData, 'XML data cannot be empty'); try { const parsedData = this._parser.parse(xmlData); if (typeof parsedData === 'object' && parsedData !== null) { const rootKeys = Object.keys(parsedData); if (rootKeys.length === 1) { const potentialArray = parsedData[rootKeys[0]]; if (Array.isArray(potentialArray)) { return potentialArray; } if (typeof potentialArray === 'object' && potentialArray !== null) { const innerKeys = Object.keys(potentialArray); if (innerKeys.length === 1 && Array.isArray(potentialArray[innerKeys[0]])) { return potentialArray[innerKeys[0]]; } if (Array.isArray(potentialArray)) { return potentialArray; } const values = Object.values(potentialArray).filter(Array.isArray); if (values.length === 1 && Array.isArray(values[0])) { return values[0]; } return [potentialArray]; } return [potentialArray]; } } return parsedData; } catch (error) { console.error('Error parsing XML:', error); throw new Error('Failed to parse XML data.'); } }; this._parser = new fast_xml_parser_1.XMLParser(Object.assign(Object.assign({}, DEFAULT_OPTIONS), options)); // Use 'as any' if type issues persist with library } } const XMLParser = new XMLParserClass(); exports.default = XMLParser;