All files / src/web/flowable validation.ts

87.81% Statements 173/197
79.56% Branches 148/186
90.9% Functions 40/44
88.35% Lines 167/189

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 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426                4x                                                           319x       99x 370x         24x                   11x 11x 3x   11x       52x 52x 52x 52x     52x     52x 52x       80x       80x 1x 1x   79x       80x 22x   80x 25x         11x 11x 11x 11x 11x 2x     11x 11x 11x               11x     11x                         80x 80x 2x         80x 80x 76x     5x 4x 1x     3x 5x 3x   2x 5x 1x           7x 7x 7x 7x 3x         1x 5x   1x     1x 1x         4x 16x   4x                     80x 80x 80x 11x   80x     80x 80x 80x 7x   80x 1x   80x 4x         24x 9x 2x 2x 2x                 24x   24x 136x 136x 52x 52x   84x 4x   80x 136x     24x 24x       22x 22x       22x               21x 20x 20x   21x 2x 2x 2x 1x                   22x 22x 20x   2x 2x 1x 1x   1x                 20x 2x   20x 2x         20x 52x     52x 1x           20x 20x 20x 52x 52x   52x 52x     20x       112x       54x 1x       20x 20x 397x 397x 80x 80x             20x                   20x 79x 79x     79x 5x   79x 4x           20x 20x         20x 20x 20x 20x 20x 20x       23x     23x 23x   1x 1x     22x       22x 22x 1x     21x   21x 20x     21x    
import { type Element as XmlElement, type Node as XmlNode } from '@xmldom/xmldom';
import type { BpmnValidationIssue } from '../shared/messages';
import {
	getActivitiAttribute,
	getElementsByLocalName,
} from './roundTrip/xmlUtils';
import { parseXmlDocument } from './xmlParser';
 
const FLOW_ELEMENTS = new Set([
	'startEvent', 'endEvent', 'userTask', 'serviceTask', 'scriptTask',
	'businessRuleTask', 'sendTask', 'receiveTask', 'manualTask', 'callActivity',
	'subProcess', 'transaction', 'exclusiveGateway', 'inclusiveGateway',
	'parallelGateway', 'eventBasedGateway', 'complexGateway',
	'boundaryEvent', 'intermediateCatchEvent', 'intermediateThrowEvent',
]);
 
interface SequenceFlow {
	id: string;
	sourceRef: string;
	targetRef: string;
	hasCondition: boolean;
}
 
interface ProcessElementCollection {
	flowNodeIds: Set<string>;
	sequenceFlows: SequenceFlow[];
	gatewaysWithoutDefault: string[];
	startEventCount: number;
	endEventCount: number;
}
 
interface FlowNodeMetadata {
	localName: string;
	skipIncomingValidation: boolean;
	skipOutgoingValidation: boolean;
}
 
function getLocalName(node: XmlNode): string {
	return node.localName || node.nodeName.split(':').pop() || node.nodeName;
}
 
function getElementChildren(element: XmlElement): XmlElement[] {
	return Array.from(element.childNodes).filter(
		(node): node is XmlElement => node.nodeType === node.ELEMENT_NODE,
	);
}
 
function createProcessElementCollection(): ProcessElementCollection {
	return {
		flowNodeIds: new Set<string>(),
		sequenceFlows: [],
		gatewaysWithoutDefault: [],
		startEventCount: 0,
		endEventCount: 0,
	};
}
 
function getExtensionFieldNames(element: XmlElement): Set<string> {
	const extensionElements = getElementChildren(element).find((child) => getLocalName(child) === 'extensionElements');
	const fields = extensionElements
		? getElementChildren(extensionElements).filter((child) => getLocalName(child) === 'field')
		: [];
	return new Set(fields.map((field) => field.getAttribute('name') || ''));
}
 
function collectSequenceFlowElement(child: XmlElement, issues: BpmnValidationIssue[], sequenceFlows: SequenceFlow[]): void {
	const id = child.getAttribute('id') || '';
	const sourceRef = child.getAttribute('sourceRef') || '';
	const targetRef = child.getAttribute('targetRef') || '';
	Iif (sourceRef === '') {
		issues.push({ elementId: id, message: `Sequence flow '${id}' is missing sourceRef`, severity: 'error' });
	}
	Iif (targetRef === '') {
		issues.push({ elementId: id, message: `Sequence flow '${id}' is missing targetRef`, severity: 'error' });
	}
	const hasCondition = getElementChildren(child).some((candidate) => getLocalName(candidate) === 'conditionExpression');
	sequenceFlows.push({ id, sourceRef, targetRef, hasCondition });
}
 
function collectFlowNodeId(localName: string, id: string, issues: BpmnValidationIssue[], flowNodeIds: Set<string>): void {
	Iif (id === '') {
		issues.push({ elementId: '', message: `${localName} element is missing an id attribute`, severity: 'error' });
		return;
	}
	if (flowNodeIds.has(id)) {
		issues.push({ elementId: id, message: `Duplicate flow node id '${id}' found in the same process`, severity: 'error' });
		return;
	}
	flowNodeIds.add(id);
}
 
function updateProcessEventCounts(localName: string, collection: ProcessElementCollection): void {
	if (localName === 'startEvent') {
		collection.startEventCount++;
	}
	if (localName === 'endEvent') {
		collection.endEventCount++;
	}
}
 
function validateServiceTaskElement(child: XmlElement, id: string, issues: BpmnValidationIssue[]): void {
	const hasClass = getActivitiAttribute(child, 'class') || child.getAttribute('class');
	const hasExpression = getActivitiAttribute(child, 'expression') || child.getAttribute('expression');
	const hasDelegate = getActivitiAttribute(child, 'delegateExpression') || child.getAttribute('delegateExpression');
	const hasType = getActivitiAttribute(child, 'type') || child.getAttribute('type');
	if (!hasClass && !hasExpression && !hasDelegate && !hasType) {
		issues.push({ elementId: id, message: `Service task '${id}' has no implementation (class, expression, delegateExpression, or type)`, severity: 'warning' });
	}
 
	const taskType = getActivitiAttribute(child, 'type') || child.getAttribute('type') || '';
	const fieldNames = getExtensionFieldNames(child);
	Iif (taskType === 'http') {
		if (!fieldNames.has('requestMethod')) {
			issues.push({ elementId: id, message: `Http task '${id}' is missing required field 'requestMethod'`, severity: 'warning' });
		}
		if (!fieldNames.has('requestUrl')) {
			issues.push({ elementId: id, message: `Http task '${id}' is missing required field 'requestUrl'`, severity: 'warning' });
		}
	}
	Iif (taskType === 'shell' && !fieldNames.has('command')) {
		issues.push({ elementId: id, message: `Shell task '${id}' is missing required field 'command'`, severity: 'warning' });
	}
	Iif (taskType === 'external-worker' && !fieldNames.has('topic')) {
		issues.push({ elementId: id, message: `External worker task '${id}' is missing required field 'topic'`, severity: 'warning' });
	}
}
 
function validateScriptTaskElement(child: XmlElement, id: string, issues: BpmnValidationIssue[]): void {
	const hasScript = getElementChildren(child).some((scriptChild) => getLocalName(scriptChild) === 'script');
	if (!hasScript) {
		issues.push({ elementId: id, message: `Script task '${id}' has no script element`, severity: 'warning' });
	}
}
 
function collectGatewayWithoutDefault(localName: string, child: XmlElement, id: string, gatewaysWithoutDefault: string[]): void {
	const isDefaultGateway = localName === 'exclusiveGateway' || localName === 'inclusiveGateway';
	if (isDefaultGateway && (child.getAttribute('default') || '') === '') {
		gatewaysWithoutDefault.push(id);
	}
}
 
function validateAsyncRetryElement(child: XmlElement, id: string, issues: BpmnValidationIssue[]): void {
	const isAsync = getActivitiAttribute(child, 'async') === 'true' || child.getAttribute('async') === 'true';
	if (!isAsync) {
		return;
	}
 
	const extensionElements = getElementChildren(child).find((candidate) => getLocalName(candidate) === 'extensionElements');
	if (!extensionElements) {
		return;
	}
 
	for (const extensionChild of getElementChildren(extensionElements)) {
		if (getLocalName(extensionChild) !== 'failedJobRetryTimeCycle') {
			continue;
		}
		const value = (extensionChild.textContent || '').trim();
		if (value && !/^R\d*\//.test(value)) {
			issues.push({ elementId: id, message: `Element '${id}' has invalid failedJobRetryTimeCycle '${value}' (expected ISO 8601 repeat pattern like R3/PT10M)`, severity: 'warning' });
		}
	}
}
 
function validateUserTaskElement(child: XmlElement, id: string, issues: BpmnValidationIssue[]): void {
	const hasAssignee = getActivitiAttribute(child, 'assignee') || child.getAttribute('assignee');
	const hasCandidateUsers = getActivitiAttribute(child, 'candidateUsers') || child.getAttribute('candidateUsers');
	const hasCandidateGroups = getActivitiAttribute(child, 'candidateGroups') || child.getAttribute('candidateGroups');
	if (!hasAssignee && !hasCandidateUsers && !hasCandidateGroups) {
		issues.push({ elementId: id, message: `User task '${id}' has no assignee or candidate users/groups`, severity: 'warning' });
	}
}
 
function validateTransactionElement(processElement: XmlElement, id: string, issues: BpmnValidationIssue[]): void {
	const boundaryEvents = getElementChildren(processElement).filter(
		(sibling) => getLocalName(sibling) === 'boundaryEvent' && sibling.getAttribute('attachedToRef') === id,
	);
	const hasCancelBoundary = boundaryEvents.some((boundaryEvent) =>
		getElementChildren(boundaryEvent).some((candidate) => getLocalName(candidate) === 'cancelEventDefinition'),
	);
	Eif (!hasCancelBoundary) {
		issues.push({ elementId: id, message: `Transaction subprocess '${id}' should have a cancel boundary event`, severity: 'warning' });
	}
}
 
function mergeCollectedSubprocess(collection: ProcessElementCollection, nested: ProcessElementCollection): void {
	for (const nodeId of nested.flowNodeIds) {
		collection.flowNodeIds.add(nodeId);
	}
	collection.sequenceFlows.push(...nested.sequenceFlows);
}
 
function validateFlowElement(
	child: XmlElement,
	localName: string,
	id: string,
	processElement: XmlElement,
	issues: BpmnValidationIssue[],
	collection: ProcessElementCollection,
): void {
	collectFlowNodeId(localName, id, issues, collection.flowNodeIds);
	updateProcessEventCounts(localName, collection);
	if (localName === 'serviceTask') {
		validateServiceTaskElement(child, id, issues);
	}
	Iif (localName === 'scriptTask') {
		validateScriptTaskElement(child, id, issues);
	}
	collectGatewayWithoutDefault(localName, child, id, collection.gatewaysWithoutDefault);
	validateAsyncRetryElement(child, id, issues);
	if (localName === 'userTask') {
		validateUserTaskElement(child, id, issues);
	}
	if (localName === 'transaction') {
		validateTransactionElement(processElement, id, issues);
	}
	if (localName === 'subProcess' || localName === 'transaction') {
		mergeCollectedSubprocess(collection, collectProcessElements(child, issues));
	}
}
 
function validateGatewayDefaultFlows(collection: ProcessElementCollection, issues: BpmnValidationIssue[]): void {
	for (const gatewayId of collection.gatewaysWithoutDefault) {
		const outgoingFlows = collection.sequenceFlows.filter((sequenceFlow) => sequenceFlow.sourceRef === gatewayId);
		const hasConditionalFlows = outgoingFlows.some((sequenceFlow) => sequenceFlow.hasCondition);
		Eif (hasConditionalFlows && outgoingFlows.length > 1) {
			issues.push({ elementId: gatewayId, message: `Gateway '${gatewayId}' has conditional flows but no default flow`, severity: 'warning' });
		}
	}
}
 
function collectProcessElements(
	processElement: XmlElement,
	issues: BpmnValidationIssue[],
): ProcessElementCollection {
	const collection = createProcessElementCollection();
 
	for (const child of getElementChildren(processElement)) {
		const localName = getLocalName(child);
		if (localName === 'sequenceFlow') {
			collectSequenceFlowElement(child, issues, collection.sequenceFlows);
			continue;
		}
		if (!FLOW_ELEMENTS.has(localName)) {
			continue;
		}
		const id = child.getAttribute('id') || '';
		validateFlowElement(child, localName, id, processElement, issues, collection);
	}
 
	validateGatewayDefaultFlows(collection, issues);
	return collection;
}
 
function validateDefinitionsRoot(document: ReturnType<typeof parseXmlDocument>, issues: BpmnValidationIssue[]): boolean {
	const definitions = document.documentElement;
	Iif (!definitions || getLocalName(definitions) !== 'definitions') {
		issues.push({ elementId: '', message: 'Missing <definitions> root element', severity: 'error' });
		return false;
	}
	return true;
}
 
function validateParticipantProcessReferences(
	document: ReturnType<typeof parseXmlDocument>,
	processes: XmlElement[],
	issues: BpmnValidationIssue[],
): void {
	const processIds = new Set(processes
		.map((process) => process.getAttribute('id') || '')
		.filter((processId) => processId !== ''));
 
	for (const participant of getElementsByLocalName(document, 'participant')) {
		const participantId = participant.getAttribute('id') || '';
		const processRef = participant.getAttribute('processRef') || '';
		if (processRef && !processIds.has(processRef)) {
			issues.push({
				elementId: participantId,
				message: `Participant '${participantId || processRef}' references non-existent process '${processRef}'`,
				severity: 'error',
			});
		}
	}
}
 
function validateProcessPresence(document: ReturnType<typeof parseXmlDocument>, issues: BpmnValidationIssue[]): XmlElement[] | undefined {
	const processes = getElementsByLocalName(document, 'process');
	if (processes.length > 0) {
		return processes;
	}
	const participants = getElementsByLocalName(document, 'participant');
	if (participants.length === 0) {
		issues.push({ elementId: '', message: 'No <process> element found in the document', severity: 'error' });
		return undefined;
	}
	return processes;
}
 
function validateProcessEventCounts(
	processId: string,
	startEventCount: number,
	endEventCount: number,
	issues: BpmnValidationIssue[],
): void {
	if (startEventCount === 0) {
		issues.push({ elementId: processId, message: `Process '${processId}' has no start event`, severity: 'warning' });
	}
	if (endEventCount === 0) {
		issues.push({ elementId: processId, message: `Process '${processId}' has no end event`, severity: 'warning' });
	}
}
 
function validateSequenceFlowReferences(sequenceFlows: SequenceFlow[], flowNodeIds: Set<string>, issues: BpmnValidationIssue[]): void {
	for (const flow of sequenceFlows) {
		Iif (flow.sourceRef && !flowNodeIds.has(flow.sourceRef)) {
			issues.push({ elementId: flow.id, message: `Sequence flow '${flow.id}' references non-existent source '${flow.sourceRef}'`, severity: 'error' });
		}
		if (flow.targetRef && !flowNodeIds.has(flow.targetRef)) {
			issues.push({ elementId: flow.id, message: `Sequence flow '${flow.id}' references non-existent target '${flow.targetRef}'`, severity: 'error' });
		}
	}
}
 
function buildNodeDirectionSets(sequenceFlows: SequenceFlow[]): { nodesWithIncoming: Set<string>; nodesWithOutgoing: Set<string> } {
	const nodesWithIncoming = new Set<string>();
	const nodesWithOutgoing = new Set<string>();
	for (const flow of sequenceFlows) {
		Eif (flow.targetRef) {
			nodesWithIncoming.add(flow.targetRef);
		}
		Eif (flow.sourceRef) {
			nodesWithOutgoing.add(flow.sourceRef);
		}
	}
	return { nodesWithIncoming, nodesWithOutgoing };
}
 
function isCompensationHandler(element: XmlElement): boolean {
	return (getActivitiAttribute(element, 'isForCompensation') || element.getAttribute('isForCompensation') || '') === 'true';
}
 
function isCompensationBoundaryEvent(element: XmlElement): boolean {
	return getLocalName(element) === 'boundaryEvent'
		&& getElementChildren(element).some((child) => getLocalName(child) === 'compensateEventDefinition');
}
 
function buildFlowNodeMetadataMap(document: ReturnType<typeof parseXmlDocument>, flowNodeIds: Set<string>): Map<string, FlowNodeMetadata> {
	const nodeMetadataMap = new Map<string, FlowNodeMetadata>();
	for (const element of Array.from(document.getElementsByTagName('*'))) {
		const elementId = element.getAttribute('id');
		if (elementId && flowNodeIds.has(elementId)) {
			const localName = getLocalName(element);
			nodeMetadataMap.set(elementId, {
				localName,
				skipIncomingValidation: localName === 'startEvent' || localName === 'boundaryEvent' || isCompensationHandler(element),
				skipOutgoingValidation: localName === 'endEvent' || isCompensationHandler(element) || isCompensationBoundaryEvent(element),
			});
		}
	}
	return nodeMetadataMap;
}
 
function validateNodeConnectivity(
	flowNodeIds: Set<string>,
	nodeMetadataMap: Map<string, FlowNodeMetadata>,
	nodesWithIncoming: Set<string>,
	nodesWithOutgoing: Set<string>,
	issues: BpmnValidationIssue[],
): void {
	for (const nodeId of flowNodeIds) {
		const metadata = nodeMetadataMap.get(nodeId);
		Iif (!metadata) {
			continue;
		}
		if (!metadata.skipIncomingValidation && !nodesWithIncoming.has(nodeId)) {
			issues.push({ elementId: nodeId, message: `Element '${nodeId}' has no incoming sequence flow`, severity: 'warning' });
		}
		if (!metadata.skipOutgoingValidation && !nodesWithOutgoing.has(nodeId)) {
			issues.push({ elementId: nodeId, message: `Element '${nodeId}' has no outgoing sequence flow`, severity: 'warning' });
		}
	}
}
 
function validateProcessElement(document: ReturnType<typeof parseXmlDocument>, process: XmlElement, issues: BpmnValidationIssue[]): void {
	const processId = process.getAttribute('id') || '';
	Iif (processId === '') {
		issues.push({ elementId: '', message: 'Process element is missing an id attribute', severity: 'error' });
		return;
	}
 
	const { flowNodeIds, sequenceFlows, startEventCount, endEventCount } = collectProcessElements(process, issues);
	validateProcessEventCounts(processId, startEventCount, endEventCount, issues);
	validateSequenceFlowReferences(sequenceFlows, flowNodeIds, issues);
	const { nodesWithIncoming, nodesWithOutgoing } = buildNodeDirectionSets(sequenceFlows);
	const nodeMetadataMap = buildFlowNodeMetadataMap(document, flowNodeIds);
	validateNodeConnectivity(flowNodeIds, nodeMetadataMap, nodesWithIncoming, nodesWithOutgoing, issues);
}
 
export function validateBpmnXml(xml: string): BpmnValidationIssue[] {
	const issues: BpmnValidationIssue[] = [];
 
	let document;
	try {
		document = parseXmlDocument(xml);
	} catch {
		issues.push({ elementId: '', message: 'Invalid XML document', severity: 'error' });
		return issues;
	}
 
	Iif (!validateDefinitionsRoot(document, issues)) {
		return issues;
	}
 
	const processes = validateProcessPresence(document, issues);
	if (!processes) {
		return issues;
	}
 
	validateParticipantProcessReferences(document, processes, issues);
 
	for (const process of processes) {
		validateProcessElement(document, process, issues);
	}
 
	return issues;
}