import { DOMParser } from 'xmldom' import { Template } from '../elements' export const resolveTemplateRefs = ( xml: string, templates: Record = {} ): string => { const parser = new DOMParser() const dom = parser.parseFromString(xml, 'text/xml') // replace template nodes with their actual content const useTemplateNodes = Array.from(dom.getElementsByTagName('UseTemplate')) useTemplateNodes.forEach((node) => { const templateName = node.getAttribute('ref') if (!templateName) return const template = templates[templateName] if (!template) return // get all the attributes const attrs = Array.from(node.attributes).reduce((acc, attr) => { if (attr.name === 'ref') return acc acc[attr.name] = attr.value return acc }, {} as Record) const templateText = template.Text // replace the variables in the template text // todo: update type // eslint-disable-next-line @typescript-eslint/no-explicit-any let text = (templateText as any)._ ?? templateText Object.entries(attrs).forEach(([key, value]) => { text = text.replace(new RegExp(`{${key}}`, 'g'), value) }) const textNode = dom.createTextNode(text) node.parentNode?.replaceChild(textNode, node) }) return dom.toString() }