UNPKG

@mos-connection/helper

Version:

Helper functions for the MOS-connection library

122 lines 3.57 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.flattenXMLText = exports.omitUndefined = exports.literal = exports.assertStringLiteral = exports.has = exports.isEmpty = void 0; function isEmpty(obj) { if (typeof obj === 'object') { for (const prop in obj) { if (has(obj, prop)) { return false; } } return JSON.stringify(obj) === JSON.stringify({}); } else { return !obj; } } exports.isEmpty = isEmpty; /** Return true if the object has a property */ function has(obj, property) { return Object.hasOwnProperty.call(obj, property); } exports.has = has; /** * Asserts that a string type is of a certain literal. * Example usage: const str = assertStringLiteral('foo', ['foo', 'bar']) // str is of type 'foo' | 'bar' */ function assertStringLiteral(value, options) { return options.includes(value); } exports.assertStringLiteral = assertStringLiteral; /** Type assertion */ function literal(o) { return o; } exports.literal = literal; /** * Removes undefined properties from an object */ function omitUndefined(obj) { if (obj && typeof obj === 'object') { for (const [key, value] of Object.entries(obj)) { if (value === undefined) delete obj[key]; } } } exports.omitUndefined = omitUndefined; function flattenXMLText(xml, strict) { const strings = []; if (typeof xml === 'object' && has(xml, 'elements')) flattenXMLTextInner(strings, xml.elements, strict); else flattenXMLTextInner(strings, xml, strict); let str = ''; let insertWhitespace = false; for (const s of strings) { if (s === '\n') { if (insertWhitespace) { str += '\n'; insertWhitespace = false; } } else { const trimmed = s.trim(); if (trimmed) { if (insertWhitespace) str += ' ' + trimmed; else str += trimmed; insertWhitespace = true; } } } return str; } exports.flattenXMLText = flattenXMLText; function flattenXMLTextInner(strings, xml, strict) { if (xml === null) { return; } else if (typeof xml === 'object') { if (Array.isArray(xml)) { for (const element of xml) { flattenXMLTextInner(strings, element, strict); } return; } else if (xml.$type === 'text' && typeof xml.text === 'string') { strings.push(xml.text); return; } else if (xml.$type === 'element') { if (xml.$name === 'p') strings.push('\n'); if (xml.$name === 'tab') strings.push(' '); for (const [key, value] of Object.entries(xml)) { if (key === '$type') continue; if (key === '$name') continue; flattenXMLTextInner(strings, value, strict); } return; } else if (typeof xml.text === 'string') { strings.push(xml.text); return; } } else if (typeof xml === 'string') { strings.push(xml); return; } else if (xml === undefined) { return; } // else if (strict) throw new Error(`flattenXMLText, unhandled value: ${JSON.stringify(xml)}`); } //# sourceMappingURL=lib.js.map