All files / src/web/flowable/roundTrip processMatching.ts

94.88% Statements 167/176
77.11% Branches 91/118
97.72% Functions 43/44
95.29% Lines 162/170

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 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372          152x     72x 4x                 228x 110x 110x 224x 224x 223x 185x     110x   191x 158x     33x   190x 190x     110x     118x 118x 118x 114x   4x             11x       27x       212x 474x 221x       442x       212x   212x 11x 11x       11x 11x 11x     212x                 106x 111x 111x 105x 105x                       106x 106x   106x 6x 6x 4x     2x 6x 6x 2x 2x 2x                   106x     4x 4x 4x           106x 2x 2x                     212x                   106x 106x 106x 110x   106x 106x 106x   106x   106x           106x               106x           106x           106x       8x 8x   8x 21x 21x 21x 12x   21x     8x       4x 4x 7x 2x     4x                   106x 106x   106x 4x 4x 4x 4x 4x 2x     2x 4x 4x   4x 4x 4x       106x 4x       4x 4x       4x     106x 106x 2x 2x       2x 2x 2x       106x       106x 106x 106x       106x       106x 2901x 2790x 106x 2819x 2709x   106x 1402x   1415x 106x 106x 20x 20x     20x 20x 20x     1415x 1402x 106x 106x 7x 7x     7x 7x 7x     106x 106x 20x 20x 18x     2x 20x 20x 2x       106x       424x 87x 2x     85x 85x 75x     10x          
import type { Document as XmlDocument, Element as XmlElement, Node as XmlNode } from '@xmldom/xmldom';
import { FLOWABLE_ATTRIBUTE_KEYS } from '../types';
import { getElementChildren, getLocalName } from './xmlUtils';
 
function compareStrings(left: string, right: string): number {
	return left.localeCompare(right);
}
 
const editableActivitiAttributes = new Set(FLOWABLE_ATTRIBUTE_KEYS.map((key) => `activiti:${key}`));
const overlayManagedChildNames = new Set([
	'extensionElements',
	'documentation',
	'conditionExpression',
	'script',
	'multiInstanceLoopCharacteristics',
]);
 
function buildComparableNodeSignature(node: XmlNode, ignoreElementId = false, structuralOnly = false): string {
	if (node.nodeType === node.ELEMENT_NODE) {
		const element = node as XmlElement;
		const attributes = Array.from(element.attributes)
			.filter((attribute) => attribute.name !== 'xmlns' && !attribute.name.startsWith('xmlns:'))
			.filter((attribute) => !(structuralOnly && editableActivitiAttributes.has(attribute.name)))
			.filter((attribute) => !(ignoreElementId && attribute.name === 'id'))
			.map((attribute) => `${attribute.name}=${attribute.value}`)
			.sort(compareStrings)
			.join('|');
		const children = Array.from(element.childNodes)
			.filter((child) => {
				if (!structuralOnly || child.nodeType !== child.ELEMENT_NODE) {
					return true;
				}
 
				return !overlayManagedChildNames.has(getLocalName(child as XmlElement));
			})
			.map((child) => buildComparableNodeSignature(child, false, structuralOnly))
			.filter((signature) => signature.length > 0)
			.join('|');
 
		return `element:${element.namespaceURI || ''}:${getLocalName(element)}:[${attributes}]:[${children}]`;
	}
 
	Eif (node.nodeType === node.TEXT_NODE || node.nodeType === node.CDATA_SECTION_NODE) {
		const value = node.nodeValue || '';
		if (value.trim().length === 0) {
			return '';
		}
		return `text:${value}`;
	}
 
	return '';
}
 
function buildProcessStructureKey(processElement: XmlElement): string {
	return buildComparableNodeSignature(processElement, true);
}
 
function buildElementStructureKey(element: XmlElement): string {
	return buildComparableNodeSignature(element, true, true);
}
 
function getProcessElements(definitions: XmlElement): XmlElement[] {
	return getElementChildren(definitions)
		.filter((child) => getLocalName(child) === 'process')
		.filter((child) => Boolean(child.getAttribute('id')));
}
 
function getUnmatchedProcesses(processes: XmlElement[], matchedIds: Set<string>): XmlElement[] {
	return processes.filter((processElement) => !matchedIds.has(processElement.getAttribute('id') || ''));
}
 
function groupProcessesByStructure(processes: XmlElement[]): Map<string, XmlElement[]> {
	const processesByStructure = new Map<string, XmlElement[]>();
 
	for (const processElement of processes) {
		const structureKey = buildProcessStructureKey(processElement);
		Iif (!structureKey) {
			continue;
		}
 
		const bucket = processesByStructure.get(structureKey) || [];
		bucket.push(processElement);
		processesByStructure.set(structureKey, bucket);
	}
 
	return processesByStructure;
}
 
function addDirectProcessMatches(
	originalProcesses: XmlElement[],
	serializedById: Map<string, XmlElement>,
	matchedOriginalIds: Set<string>,
	matchedSerializedIds: Set<string>,
): void {
	for (const processElement of originalProcesses) {
		const processId = processElement.getAttribute('id') || '';
		if (serializedById.has(processId)) {
			matchedOriginalIds.add(processId);
			matchedSerializedIds.add(processId);
		}
	}
}
 
function addStructureBasedProcessMatches(
	renameMap: Map<string, string>,
	originalProcesses: XmlElement[],
	serializedProcesses: XmlElement[],
	matchedOriginalIds: Set<string>,
	matchedSerializedIds: Set<string>,
): void {
	const originalByStructure = groupProcessesByStructure(originalProcesses);
	const serializedByStructure = groupProcessesByStructure(serializedProcesses);
 
	for (const [structureKey, originalMatches] of originalByStructure.entries()) {
		const serializedMatches = serializedByStructure.get(structureKey);
		if (!serializedMatches || originalMatches.length !== 1 || serializedMatches.length !== 1) {
			continue;
		}
 
		const originalId = originalMatches[0].getAttribute('id') || '';
		const serializedId = serializedMatches[0].getAttribute('id') || '';
		if (originalId && serializedId && originalId !== serializedId) {
			renameMap.set(originalId, serializedId);
			matchedOriginalIds.add(originalId);
			matchedSerializedIds.add(serializedId);
		}
	}
}
 
function addDescendantBasedProcessMatches(
	renameMap: Map<string, string>,
	originalProcesses: XmlElement[],
	serializedProcesses: XmlElement[],
): void {
	const descendantIdRenameMatches = findUniqueBestBidirectionalMatches(
		originalProcesses,
		serializedProcesses,
		(processElement) => processElement.getAttribute('id') || '',
		(processElement) => processElement.getAttribute('id') || '',
		(leftProcess, rightProcess) => countSharedSetValues(
			collectDescendantElementIds(leftProcess),
			collectDescendantElementIds(rightProcess),
		),
	);
 
	for (const [originalId, serializedId] of descendantIdRenameMatches.entries()) {
		Eif (originalId !== serializedId) {
			renameMap.set(originalId, serializedId);
		}
	}
}
 
function getRemainingProcessSets(
	originalProcesses: XmlElement[],
	serializedProcesses: XmlElement[],
	matchedOriginalIds: Set<string>,
	matchedSerializedIds: Set<string>,
): { originalProcesses: XmlElement[]; serializedProcesses: XmlElement[] } {
	return {
		originalProcesses: getUnmatchedProcesses(originalProcesses, matchedOriginalIds),
		serializedProcesses: getUnmatchedProcesses(serializedProcesses, matchedSerializedIds),
	};
}
 
function buildProcessIdRenameMapForDefinitions(
	originalDefinitions: XmlElement,
	serializedDefinitions: XmlElement,
): Map<string, string> {
	const originalProcesses = getProcessElements(originalDefinitions);
	const serializedProcesses = getProcessElements(serializedDefinitions);
	const serializedById = new Map(
		serializedProcesses.map((processElement) => [processElement.getAttribute('id') || '', processElement] as const),
	);
	const matchedOriginalIds = new Set<string>();
	const matchedSerializedIds = new Set<string>();
	const renameMap = new Map<string, string>();
 
	addDirectProcessMatches(originalProcesses, serializedById, matchedOriginalIds, matchedSerializedIds);
 
	const structureCandidates = getRemainingProcessSets(
		originalProcesses,
		serializedProcesses,
		matchedOriginalIds,
		matchedSerializedIds,
	);
	addStructureBasedProcessMatches(
		renameMap,
		structureCandidates.originalProcesses,
		structureCandidates.serializedProcesses,
		matchedOriginalIds,
		matchedSerializedIds,
	);
 
	const descendantCandidates = getRemainingProcessSets(
		originalProcesses,
		serializedProcesses,
		matchedOriginalIds,
		matchedSerializedIds,
	);
	addDescendantBasedProcessMatches(
		renameMap,
		descendantCandidates.originalProcesses,
		descendantCandidates.serializedProcesses,
	);
 
	return renameMap;
}
 
function collectDescendantElementIds(element: XmlElement): Set<string> {
	const descendantIds = new Set<string>();
	const queue = [...getElementChildren(element)];
 
	while (queue.length > 0) {
		const [current] = queue.splice(0, 1);
		const id = current.getAttribute('id');
		if (id) {
			descendantIds.add(id);
		}
		queue.push(...getElementChildren(current));
	}
 
	return descendantIds;
}
 
function countSharedSetValues(left: Set<string>, right: Set<string>): number {
	let sharedCount = 0;
	for (const value of left) {
		if (right.has(value)) {
			sharedCount += 1;
		}
	}
	return sharedCount;
}
 
function findUniqueBestBidirectionalMatches<T, U>(
	leftItems: T[],
	rightItems: U[],
	getLeftId: (item: T) => string,
	getRightId: (item: U) => string,
	getScore: (left: T, right: U) => number,
): Map<string, string> {
	const leftCandidates = new Map<string, Array<{ id: string; score: number }>>();
	const rightCandidates = new Map<string, Array<{ id: string; score: number }>>();
 
	for (const leftItem of leftItems) {
		const leftId = getLeftId(leftItem);
		for (const rightItem of rightItems) {
			const rightId = getRightId(rightItem);
			const score = getScore(leftItem, rightItem);
			if (score <= 0) {
				continue;
			}
 
			const leftBucket = leftCandidates.get(leftId) || [];
			leftBucket.push({ id: rightId, score });
			leftCandidates.set(leftId, leftBucket);
 
			const rightBucket = rightCandidates.get(rightId) || [];
			rightBucket.push({ id: leftId, score });
			rightCandidates.set(rightId, rightBucket);
		}
	}
 
	const selectUniqueBestMatch = (candidates: Array<{ id: string; score: number }> | undefined): string | undefined => {
		Iif (!candidates || candidates.length === 0) {
			return undefined;
		}
 
		const sortedCandidates = [...candidates].sort((left, right) => right.score - left.score);
		Iif (sortedCandidates.length > 1 && sortedCandidates[0].score === sortedCandidates[1].score) {
			return undefined;
		}
 
		return sortedCandidates[0].id;
	};
 
	const matches = new Map<string, string>();
	for (const [leftId, candidates] of leftCandidates.entries()) {
		const rightId = selectUniqueBestMatch(candidates);
		Iif (!rightId) {
			continue;
		}
 
		const reverseMatch = selectUniqueBestMatch(rightCandidates.get(rightId));
		Eif (reverseMatch === leftId) {
			matches.set(leftId, rightId);
		}
	}
 
	return matches;
}
 
export function buildProcessIdRenameMap(originalDocument: XmlDocument, serializedDocument: XmlDocument): Map<string, string> {
	const originalDefinitions = originalDocument.documentElement;
	const serializedDefinitions = serializedDocument.documentElement;
	Iif (!originalDefinitions || !serializedDefinitions) {
		return new Map();
	}
 
	return buildProcessIdRenameMapForDefinitions(originalDefinitions, serializedDefinitions);
}
 
export function buildElementIdRenameMap(originalDocument: XmlDocument, serializedDocument: XmlDocument): Map<string, string> {
	const originalElements = Array.from(originalDocument.getElementsByTagName('*'))
		.filter((element) => getLocalName(element) !== 'process')
		.filter((element) => Boolean(element.getAttribute('id')));
	const serializedElements = Array.from(serializedDocument.getElementsByTagName('*'))
		.filter((element) => getLocalName(element) !== 'process')
		.filter((element) => Boolean(element.getAttribute('id')));
 
	const serializedById = new Map(
		serializedElements.map((element) => [element.getAttribute('id') || '', element] as const),
	);
	const unmatchedOriginalElements = originalElements.filter((element) => !serializedById.has(element.getAttribute('id') || ''));
	const originalByStructure = new Map<string, XmlElement[]>();
	for (const element of unmatchedOriginalElements) {
		const structureKey = buildElementStructureKey(element);
		Iif (!structureKey) {
			continue;
		}
		const bucket = originalByStructure.get(structureKey) || [];
		bucket.push(element);
		originalByStructure.set(structureKey, bucket);
	}
 
	const originalById = new Map(originalElements.map((element) => [element.getAttribute('id') || '', element] as const));
	const unmatchedSerializedElements = serializedElements.filter((element) => !originalById.has(element.getAttribute('id') || ''));
	const serializedByStructure = new Map<string, XmlElement[]>();
	for (const element of unmatchedSerializedElements) {
		const structureKey = buildElementStructureKey(element);
		Iif (!structureKey) {
			continue;
		}
		const bucket = serializedByStructure.get(structureKey) || [];
		bucket.push(element);
		serializedByStructure.set(structureKey, bucket);
	}
 
	const renameMap = new Map<string, string>();
	for (const [structureKey, originalMatches] of originalByStructure.entries()) {
		const serializedMatches = serializedByStructure.get(structureKey);
		if (!serializedMatches || originalMatches.length !== 1 || serializedMatches.length !== 1) {
			continue;
		}
 
		const originalId = originalMatches[0].getAttribute('id') || '';
		const serializedId = serializedMatches[0].getAttribute('id') || '';
		if (originalId && serializedId && originalId !== serializedId) {
			renameMap.set(originalId, serializedId);
		}
	}
 
	return renameMap;
}
 
export function remapProcessScopedItems<T extends { processId?: string }>(items: T[], processIdRenameMap: Map<string, string>): T[] {
	return items.map((item) => {
		if (!item.processId) {
			return { ...item };
		}
 
		const nextProcessId = processIdRenameMap.get(item.processId);
		if (!nextProcessId || nextProcessId === item.processId) {
			return { ...item };
		}
 
		return {
			...item,
			processId: nextProcessId,
		};
	});
}