UNPKG

@nodecfdi/cfdi-cleaner

Version:

Librería para limpiar comprobantes fiscales digitales v3.3 y v4.0

40 lines (39 loc) 1.81 kB
import { Mixin } from 'ts-mixer'; import xpath from 'xpath'; import XmlNamespaceMethods from '#src/mixins/xml_namespace_methods'; export default class RemoveUnusedNamespaces extends Mixin(XmlNamespaceMethods) { clean(document) { for (const namespaceNode of this.iterateNonReservedNamespaces(document)) { this.checkNamespaceNode(document, namespaceNode); } } hasElementsOnNamespace(document, namespace, prefix) { const elements = xpath.select(`//*[namespace-uri()="${namespace}" and name()=concat("${prefix}", local-name())]`, // @ts-expect-error misssing Node properties are not needed document); return Boolean(elements && elements.length > 0); } hasAttributesOnNamespace(document, namespace, prefix) { const attributes = xpath.select(`//@*[namespace-uri()="${namespace}" and name()=concat("${prefix}", local-name())]`, // @ts-expect-error misssing Node properties are not needed document); return Boolean(attributes && attributes.length > 0); } checkNamespaceNode(document, namespaceNode) { const namespace = namespaceNode.nodeValue; /* istanbul ignore if -- For usage always is not null but for default nodeValue is posible null @preserve */ if (namespace === null) { return; } const localName = `${namespaceNode.localName}:`; if (!this.isPrefixedNamespaceOnUse(document, namespace, localName)) { this.removeNamespaceNodeAttribute(namespaceNode); } } isPrefixedNamespaceOnUse(document, namespace, prefix) { if (this.hasElementsOnNamespace(document, namespace, prefix)) { return true; } return this.hasAttributesOnNamespace(document, namespace, prefix); } }