All files / src/xml-manipulation index.ts

97.94% Statements 95/97
92.42% Branches 61/66
100% Functions 22/22
97.83% Lines 90/92

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270                                                                          69x       77x       187x       171x         160x       76x       84x 5x     79x 10x     69x 64x 28x     36x 7x     29x     31x   5x   26x 4x     25x     5x       48x     48x 104x 104x 88x 48x   16x   48x             53x 9x 9x   44x 5x     39x   39x 89x 89x 47x 47x   42x     39x 39x 39x       40x 11x         29x 5x         24x           24x 24x       24x 19x   24x 16x   24x           44x 39x 51x           39x   5x             32x       32x       32x 25x   32x             68x 10x             58x 5x             53x 21x       21x 21x 21x   21x     32x 32x   32x 32x       32x 32x   32x             21x 21x 21x       21x 21x       21x    
import { Element, js2xml, xml2js, Attributes } from 'xml-js';
 
import { readFileWithFallback, createDirAndWriteFile } from '../file-helpers';
 
type ExplicitNewValue<T> = { newValue: T };
type WithExplicitNewValue<T> = T | ExplicitNewValue<T>;
 
type ExpectedElementAttributes = Record<string, WithExplicitNewValue<string | number | undefined>>;
type WithExplicitIndex<T> = T & { idx?: number };
 
type ExpectedElements = WithExplicitNewValue<WithExplicitIndex<ExpectedElement>[]>;
 
export type ExpectedElementType = {
  name: string;
  attributes?: ExpectedElementAttributes;
  elements?: ExpectedElements;
};
 
export type ExpectedElementsType = {
  elements: ExpectedElements;
};
 
export type ExpectedCommentType = {
  comment: string;
};
 
export type ExpectedTextType = {
  text: string | number | boolean;
};
 
export type ExpectedElement =
  | ExpectedElementType
  | ExpectedElementsType
  | ExpectedCommentType
  | ExpectedTextType;
 
function isElementType(el: ExpectedElement): el is ExpectedElementType {
  return (el as ExpectedElementType).name !== undefined;
}
 
function isElementsType(el: ExpectedElement): el is ExpectedElementsType {
  return !(el as ExpectedElementType).name && Boolean((el as ExpectedElementsType).elements);
}
 
function isCommentType(el: ExpectedElement): el is ExpectedCommentType {
  return (el as ExpectedCommentType).comment !== undefined;
}
 
function isTextType(el: ExpectedElement): el is ExpectedTextType {
  return (el as ExpectedTextType).text !== undefined;
}
 
function isExplicitNewValue<T>(el: WithExplicitNewValue<T>): el is ExplicitNewValue<T> {
  // @ts-ignore
  return typeof el === 'object' && el.hasOwnProperty('newValue');
}
 
function unboxExplicitNewValue<T>(el: WithExplicitNewValue<T>): T {
  return isExplicitNewValue(el) ? el.newValue : el;
}
 
function compareElements(element: Element, expectedElement: ExpectedElement): boolean {
  if (isTextType(expectedElement)) {
    return element.type === 'text';
  }
 
  if (isCommentType(expectedElement)) {
    return element.type === 'comment' && element.comment?.trim() === expectedElement.comment.trim();
  }
 
  if (isElementType(expectedElement) && element.type === 'element') {
    if (expectedElement.name !== element.name) {
      return false;
    }
 
    if (!element.attributes) {
      return true;
    }
 
    for (const [key, value] of Object.entries(
      (expectedElement as ExpectedElementType).attributes || {}
    )) {
      if (isExplicitNewValue(value)) {
        // this attribute has to be overridden
        continue;
      }
      if (element.attributes[key] !== value) {
        return false;
      }
    }
    return true;
  }
 
  return false;
}
 
function sortWithExplicitIndex<T>(elements?: WithExplicitIndex<T>[]): T[] | undefined {
  Iif (!elements) {
    return;
  }
  const result: T[] = new Array(elements.length);
  const elementsWithExplicitIndices = elements.filter(({ idx }) => idx !== undefined);
  const elementsWithoutExplicitIndices = elements.filter(({ idx }) => idx === undefined);
  elementsWithoutExplicitIndices.forEach((el, idx) => (result[idx] = el));
  elementsWithExplicitIndices.forEach(({ idx, ...el }, i) => {
    // @ts-ignore
    result.splice(idx ?? i, 0, el);
  });
  return result;
}
 
function mergeXmlElementsLists(
  current?: Element[],
  expected?: ExpectedElements
): Element[] | undefined {
  if (isExplicitNewValue(expected) || !current) {
    const sortedExpected = sortWithExplicitIndex(unboxExplicitNewValue(expected));
    return sortedExpected?.map(convertToElement);
  }
  if (!expected) {
    return current;
  }
 
  const result: WithExplicitIndex<Element>[] = [];
 
  for (const currentElement of current) {
    const idxInExpected = expected.findIndex(el => compareElements(currentElement, el));
    if (idxInExpected !== -1) {
      const { idx, ...element } = expected.splice(idxInExpected, 1)[0];
      result.push({ idx, ...mergeXmlElements(currentElement, element) });
    } else {
      result.push(currentElement);
    }
  }
  result.push(...expected.map(({ idx, ...el }) => ({ idx, ...convertToElement(el) })));
  const sortedResult = sortWithExplicitIndex(result);
  return sortedResult;
}
 
function convertToElement(expectedElement: ExpectedElement): Element {
  if (isCommentType(expectedElement)) {
    return {
      ...expectedElement,
      type: 'comment',
    };
  }
  if (isTextType(expectedElement)) {
    return {
      ...expectedElement,
      type: 'text',
    };
  }
  Iif (isElementsType(expectedElement)) {
    return {
      elements: unboxExplicitNewValue(expectedElement.elements).map(convertToElement),
      type: 'element',
    };
  }
  const { elements, attributes, ...expectedRest } = expectedElement;
  const result: Element = {
    ...expectedRest,
    type: 'element',
  };
  if (attributes) {
    result.attributes = convertExpectedAttributes(attributes);
  }
  if (elements) {
    result.elements = unboxExplicitNewValue(elements).map(convertToElement);
  }
  return result;
}
 
function convertExpectedAttributes(
  expectedAttributes?: ExpectedElementAttributes
): Attributes | undefined {
  if (expectedAttributes) {
    const result = Object.entries(expectedAttributes).reduce(
      (acc, [key, value]) => ({
        ...acc,
        [key]: unboxExplicitNewValue(value),
      }),
      {}
    );
    return result;
  }
  return undefined;
}
 
function mergeAndConvertToElement(
  { attributes: currentAttributes, ...currentRest }: Omit<Element, 'elements'>,
  { attributes: expectedAttributes, ...expectedRest }: Omit<ExpectedElementType, 'elements'>
): Element {
  const result: Element = {
    ...currentRest,
    ...expectedRest,
  };
  const attributes = (currentAttributes || expectedAttributes) && {
    ...currentAttributes,
    ...convertExpectedAttributes(expectedAttributes),
  };
  if (attributes) {
    result.attributes = attributes;
  }
  return result;
}
 
/**
 * Assumption is that elements are `equal` semantically
 */
export function mergeXmlElements(current: Element, expected: ExpectedElement): Element {
  if (isCommentType(expected)) {
    return {
      ...current,
      ...expected,
      type: 'comment',
    };
  }
 
  if (isTextType(expected)) {
    return {
      ...current,
      ...expected,
      type: 'text',
    };
  }
 
  if (isElementsType(expected)) {
    const result = {
      ...current,
      type: 'element',
    };
    const elements = mergeXmlElementsLists(current.elements, expected.elements);
    Eif (elements) {
      result.elements = elements;
    }
    return result;
  }
 
  const { elements: currentElements, ...currentRest } = current;
  const { elements: expectedElements, ...expectedRest } = expected;
 
  const elements = mergeXmlElementsLists(current.elements, expected.elements);
  const result = {
    ...mergeAndConvertToElement(currentRest, expectedRest),
    type: 'element',
  };
  Eif (elements) {
    result.elements = elements;
  }
  return result;
}
 
export async function readXmlFile(
  filePath: string,
  fallbackContent: string = `<?xml version="1.0" encoding="utf-8"?>`
): Promise<Element> {
  const fileContent = await readFileWithFallback(filePath, fallbackContent);
  const fileXml = xml2js(fileContent);
  return fileXml as Element;
}
 
export async function writeXmlFile(filePath: string, xml: Element) {
  const fileXml = js2xml(xml, { indentAttributes: true, spaces: 2 });
  const correctedFile = fileXml.replace(
    /(?<openTag><[^\s]+)\n *(?<firstAttribute> [^\s]+=".+?")\n *((?<secondAttribute> [^\s]+=".+?")\n *)?(?<closeTag>[/?]?>)/g,
    '$1$2$4$5'
  );
  await createDirAndWriteFile(filePath, `${correctedFile}\n`);
}