rflib-plugin 0.20.0 → 0.21.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,10 +9,15 @@ import * as path from 'node:path';
9
9
  import { Messages, Logger } from '@salesforce/core';
10
10
  import { SfCommand, Flags } from '@salesforce/sf-plugins-core';
11
11
  import * as xml2js from 'xml2js';
12
- import { minimatch } from 'minimatch';
13
12
  import { processWithConcurrency } from '../../../../shared/concurrency.js';
13
+ import { isExcluded } from '../../../../shared/exclude.js';
14
+ import { compareVersions, formatVersion, getInstalledPackages, } from '../../../../shared/packageClient.js';
14
15
  Messages.importMessagesDirectoryFromMetaUrl(import.meta.url);
15
16
  const messages = Messages.loadMessages('rflib-plugin', 'rflib.logging.flow.instrument');
17
+ const RFLIB_PACKAGE_NAME = 'RFLIB';
18
+ // First RFLIB version whose Log Message flow action has the Terminate Transaction option,
19
+ // which the fault paths created by this command rely on
20
+ const FAULT_PATH_MIN_RFLIB_VERSION = { major: 11, minor: 4, patch: 0, build: 0 };
16
21
  export class FlowInstrumentationService {
17
22
  static parser = new xml2js.Parser({
18
23
  explicitArray: false,
@@ -28,6 +33,43 @@ export class FlowInstrumentationService {
28
33
  newline: '\n'
29
34
  }
30
35
  });
36
+ // Flow element types that support a fault connector, mapped to the name used in Flow Builder
37
+ static FAULT_CAPABLE_ELEMENTS = {
38
+ actionCalls: 'Action',
39
+ apexPluginCalls: 'Apex Plugin',
40
+ recordCreates: 'Create Records',
41
+ recordDeletes: 'Delete Records',
42
+ recordLookups: 'Get Records',
43
+ recordUpdates: 'Update Records',
44
+ waits: 'Wait',
45
+ };
46
+ // Keys common to all flow elements, which precede the type specific keys in the metadata
47
+ static BASE_ELEMENT_KEYS = new Set([
48
+ 'processMetadataValues',
49
+ 'description',
50
+ 'name',
51
+ 'n',
52
+ 'elementSubtype',
53
+ 'label',
54
+ 'locationX',
55
+ 'locationY',
56
+ ]);
57
+ // Keys whose element references are outputs or navigation rather than inputs of an element
58
+ static NON_INPUT_KEYS = new Set([
59
+ 'connector',
60
+ 'faultConnector',
61
+ 'outputAssignments',
62
+ 'outputParameters',
63
+ 'processMetadataValues',
64
+ ]);
65
+ // Screen field types that hold a single input value
66
+ static SCALAR_SCREEN_FIELD_TYPES = new Set([
67
+ 'InputField',
68
+ 'LargeTextArea',
69
+ 'DropdownBox',
70
+ 'RadioButtons',
71
+ ]);
72
+ static MAX_FAULT_LOG_REFERENCES = 10;
31
73
  static async parseFlowContent(content) {
32
74
  try {
33
75
  return await this.parser.parseStringPromise(content);
@@ -76,10 +118,14 @@ export class FlowInstrumentationService {
76
118
  const actionCalls = Array.isArray(flowObj.Flow.actionCalls)
77
119
  ? flowObj.Flow.actionCalls
78
120
  : [flowObj.Flow.actionCalls];
79
- return actionCalls.some((action) => action.actionName === 'rflib:Logger' ||
80
- action.actionName === 'rflib_LoggerFlowAction' ||
81
- action.actionName === 'rflib_ApplicationEventLoggerAction' ||
82
- (action.name && typeof action.name === 'string' && action.name.startsWith('RFLIB_Flow_Logger')));
121
+ return actionCalls.some((action) => this.isRFLIBLoggerAction(action));
122
+ }
123
+ // Helper to check if a single action call is an RFLIB logging action
124
+ static isRFLIBLoggerAction(action) {
125
+ return (action?.actionName === 'rflib:Logger' ||
126
+ action?.actionName === 'rflib_LoggerFlowAction' ||
127
+ action?.actionName === 'rflib_ApplicationEventLoggerAction' ||
128
+ (typeof action?.name === 'string' && action.name.startsWith('RFLIB_Flow_Logger')));
83
129
  }
84
130
  // Helper to check if flow has a supported process type for instrumentation
85
131
  static isSupportedProcessType(flowObj) {
@@ -89,7 +135,7 @@ export class FlowInstrumentationService {
89
135
  (processType === 'AutoLaunchedFlow' && triggerType === 'RecordAfterSave');
90
136
  }
91
137
  // Main instrumentation function
92
- static instrumentFlow(flowObj, flowName, skipInstrumented = false) {
138
+ static instrumentFlow(flowObj, flowName, skipInstrumented = false, skipFaultPaths = false) {
93
139
  // Deep clone the object to avoid modifying the original
94
140
  const instrumentedFlow = JSON.parse(JSON.stringify(flowObj));
95
141
  // Skip if already instrumented and skipInstrumented flag is set
@@ -142,6 +188,10 @@ export class FlowInstrumentationService {
142
188
  if (instrumentedFlow.Flow.decisions) {
143
189
  this.instrumentDecisions(instrumentedFlow, flowName);
144
190
  }
191
+ // Log an error on every fault path of elements that can fail
192
+ if (!skipFaultPaths) {
193
+ this.instrumentFaultPaths(instrumentedFlow, flowName);
194
+ }
145
195
  // Reorder Flow properties
146
196
  const originalFlow = instrumentedFlow.Flow;
147
197
  const orderedFlow = {
@@ -229,6 +279,153 @@ export class FlowInstrumentationService {
229
279
  flowObj.Flow.actionCalls = [actionCall, flowObj.Flow.actionCalls];
230
280
  }
231
281
  }
282
+ // Helper to add error logging to the fault path of every element that can fail.
283
+ // Existing fault paths continue after the logger; new fault paths terminate the transaction
284
+ // after logging so that the flow fails the same way as without a fault path.
285
+ static instrumentFaultPaths(flowObj, flowName) {
286
+ // Fault paths starting with one of these actions are already logged, e.g. by a previous run
287
+ const logMessageActionNames = new Set(this.toArray(flowObj.Flow.actionCalls)
288
+ .filter((action) => this.isRFLIBLoggerAction(action) && action.actionName !== 'rflib_ApplicationEventLoggerAction')
289
+ .map((action) => this.getElementName(action)));
290
+ const scalarResourceNames = this.collectScalarResourceNames(flowObj);
291
+ Object.entries(this.FAULT_CAPABLE_ELEMENTS).forEach(([elementType, elementTypeLabel]) => {
292
+ // Copy the list since fault loggers are added to actionCalls while iterating
293
+ const elements = [...this.toArray(flowObj.Flow[elementType])];
294
+ elements.forEach((element) => {
295
+ const elementName = this.getElementName(element);
296
+ if (!elementName || (elementType === 'actionCalls' && this.isRFLIBLoggerAction(element))) {
297
+ return;
298
+ }
299
+ const originalFaultConnector = element.faultConnector;
300
+ const originalTarget = originalFaultConnector?.targetReference;
301
+ if (typeof originalTarget === 'string' && logMessageActionNames.has(originalTarget)) {
302
+ return;
303
+ }
304
+ const faultLogger = this.createFaultPathLogger(flowName, elementTypeLabel, elementName, String(element.label || elementName), this.collectFaultLogReferences(flowObj, element, scalarResourceNames), !originalTarget);
305
+ if (originalTarget) {
306
+ // Continue with the existing fault path, keeping connector properties such as isGoTo
307
+ faultLogger.connector = { ...originalFaultConnector };
308
+ }
309
+ this.addActionCallToFlow(flowObj, faultLogger);
310
+ this.setFaultConnector(element, { targetReference: faultLogger.name });
311
+ });
312
+ });
313
+ }
314
+ // Helper to create the error logging action for a fault path
315
+ static createFaultPathLogger(flowName, elementTypeLabel, elementName, elementLabel, references, terminateTransaction) {
316
+ const loggerId = this.generateUniqueId();
317
+ const prefix = 'RFLIB_Flow_Logger_Fault_';
318
+ // Keep the name under 80 characters: prefix + element name + '_' + id
319
+ const sanitizedElementName = this.sanitizeForName(elementName, 80 - prefix.length - loggerId.length - 1);
320
+ const name = `${prefix}${sanitizedElementName}_${loggerId}`;
321
+ const label = this.truncateLabel(`Log Fault: ${elementLabel}`);
322
+ const values = references.map((reference) => `${reference}: {!${reference}}`).join(', ');
323
+ const message = `Fault in ${elementTypeLabel} '${elementLabel}' (${elementName}): {!$Flow.FaultMessage}` +
324
+ (values ? ` | ${values}` : '');
325
+ const additionalParameters = terminateTransaction
326
+ ? [{ name: 'terminateTransaction', value: { booleanValue: 'true' } }]
327
+ : [];
328
+ return this.buildLoggerAction(name, label, flowName, 'ERROR', message, additionalParameters);
329
+ }
330
+ // Helper to collect the resources whose values are logged when an element faults: the scalar inputs
331
+ // of the element, the triggering record and the input variables of the flow
332
+ static collectFaultLogReferences(flowObj, element, scalarResourceNames) {
333
+ const references = [];
334
+ const addReference = (reference) => {
335
+ if (typeof reference !== 'string' || references.includes(reference)) {
336
+ return;
337
+ }
338
+ // Global variables other than the triggering record, such as $Api or $Setup, may hold sensitive values
339
+ if (reference.startsWith('$') && !/^\$Record(__Prior)?\./.test(reference)) {
340
+ return;
341
+ }
342
+ if (reference.includes('.') || scalarResourceNames.has(reference)) {
343
+ references.push(reference);
344
+ }
345
+ };
346
+ this.findElementReferences(element).forEach(addReference);
347
+ const triggerType = flowObj.Flow.start?.triggerType;
348
+ if (typeof triggerType === 'string' && triggerType.startsWith('Record')) {
349
+ addReference('$Record.Id');
350
+ }
351
+ this.toArray(flowObj.Flow.variables)
352
+ .filter((variable) => variable.isInput === 'true')
353
+ .forEach((variable) => addReference(this.getElementName(variable)));
354
+ return references.slice(0, this.MAX_FAULT_LOG_REFERENCES);
355
+ }
356
+ // Helper to find all element references within an element that are used as inputs
357
+ static findElementReferences(node, references = []) {
358
+ if (Array.isArray(node)) {
359
+ node.forEach((item) => this.findElementReferences(item, references));
360
+ }
361
+ else if (node && typeof node === 'object') {
362
+ Object.entries(node).forEach(([key, value]) => {
363
+ if (this.NON_INPUT_KEYS.has(key)) {
364
+ return;
365
+ }
366
+ if (key === 'elementReference' && typeof value === 'string') {
367
+ references.push(value);
368
+ }
369
+ else {
370
+ this.findElementReferences(value, references);
371
+ }
372
+ });
373
+ }
374
+ return references;
375
+ }
376
+ // Helper to collect the names of flow resources that hold a single value and can be merged into a text
377
+ static collectScalarResourceNames(flowObj) {
378
+ const names = new Set();
379
+ const addName = (resource) => {
380
+ const name = this.getElementName(resource);
381
+ if (name) {
382
+ names.add(name);
383
+ }
384
+ };
385
+ this.toArray(flowObj.Flow.variables)
386
+ .filter((variable) => variable.isCollection !== 'true' && variable.dataType !== 'SObject' && variable.dataType !== 'Apex')
387
+ .forEach((variable) => addName(variable));
388
+ this.toArray(flowObj.Flow.formulas).forEach((formula) => addName(formula));
389
+ const addScreenFields = (fields) => {
390
+ this.toArray(fields).forEach((field) => {
391
+ if (this.SCALAR_SCREEN_FIELD_TYPES.has(String(field.fieldType))) {
392
+ addName(field);
393
+ }
394
+ // Sections and columns contain nested fields
395
+ addScreenFields(field.fields);
396
+ });
397
+ };
398
+ this.toArray(flowObj.Flow.screens).forEach((screen) => addScreenFields(screen.fields));
399
+ return names;
400
+ }
401
+ // Helper to set the fault connector of an element. The Metadata API expects the fault connector
402
+ // at its alphabetical position among the element's type specific properties.
403
+ static setFaultConnector(element, faultConnector) {
404
+ if (element.faultConnector !== undefined) {
405
+ element.faultConnector = faultConnector;
406
+ return;
407
+ }
408
+ const entries = Object.entries(element);
409
+ const insertIndex = entries.findIndex(([key]) => !this.BASE_ELEMENT_KEYS.has(key) && key > 'faultConnector');
410
+ entries.splice(insertIndex === -1 ? entries.length : insertIndex, 0, ['faultConnector', faultConnector]);
411
+ // Rebuild the element in place to preserve references held by the flow object
412
+ Object.keys(element).forEach((key) => Reflect.deleteProperty(element, key));
413
+ entries.forEach(([key, value]) => {
414
+ element[key] = value;
415
+ });
416
+ }
417
+ // Helper to read the name of a flow element, supporting the legacy 'n' property
418
+ static getElementName(element) {
419
+ const name = element?.name ?? element?.n;
420
+ return typeof name === 'string' && name ? name : undefined;
421
+ }
422
+ // Helper to normalize a single parsed XML element or a list of elements to an array
423
+ static toArray(value) {
424
+ if (value === undefined || value === null) {
425
+ return [];
426
+ }
427
+ return Array.isArray(value) ? value : [value];
428
+ }
232
429
  // Helper to create a logging action for decision paths
233
430
  static createDecisionPathLogger(flowName, decisionName, decisionLabel, outcomeName, outcomeLabel) {
234
431
  const loggerId = this.generateUniqueId();
@@ -250,37 +447,12 @@ export class FlowInstrumentationService {
250
447
  const name = `RFLIB_Flow_Logger_Decision_${sanitizedDecisionName}_${sanitizedOutcomeName}_${loggerId}`;
251
448
  // Create and truncate the label to ensure it's under 80 chars
252
449
  const label = this.truncateLabel(`Log Decision: ${decisionLabelStr} - ${outcomeLabelStr}`);
450
+ const message = `Decision '${decisionLabelStr}' outcome: ${outcomeLabelStr}`;
253
451
  // Fallback if still too long
254
- if (name.length > 80) {
255
- return {
256
- actionName: 'rflib_LoggerFlowAction',
257
- actionType: 'apex',
258
- name: `RFLIBLogDec${loggerId}`,
259
- label,
260
- locationX: 176,
261
- locationY: 50,
262
- inputParameters: [
263
- {
264
- name: 'context',
265
- value: {
266
- stringValue: flowName,
267
- },
268
- },
269
- {
270
- name: 'logLevel',
271
- value: {
272
- stringValue: 'INFO',
273
- },
274
- },
275
- {
276
- name: 'message',
277
- value: {
278
- stringValue: `Decision '${decisionLabelStr}' outcome: ${outcomeLabelStr}`,
279
- },
280
- },
281
- ],
282
- };
283
- }
452
+ return this.buildLoggerAction(name.length > 80 ? `RFLIBLogDec${loggerId}` : name, label, flowName, 'INFO', message);
453
+ }
454
+ // Helper to build an rflib_LoggerFlowAction action call element
455
+ static buildLoggerAction(name, label, context, logLevel, message, additionalParameters = []) {
284
456
  return {
285
457
  actionName: 'rflib_LoggerFlowAction',
286
458
  actionType: 'apex',
@@ -292,21 +464,22 @@ export class FlowInstrumentationService {
292
464
  {
293
465
  name: 'context',
294
466
  value: {
295
- stringValue: flowName,
467
+ stringValue: context,
296
468
  },
297
469
  },
298
470
  {
299
471
  name: 'logLevel',
300
472
  value: {
301
- stringValue: 'INFO',
473
+ stringValue: logLevel,
302
474
  },
303
475
  },
304
476
  {
305
477
  name: 'message',
306
478
  value: {
307
- stringValue: `Decision '${decisionLabelStr}' outcome: ${outcomeLabelStr}`,
479
+ stringValue: message,
308
480
  },
309
481
  },
482
+ ...additionalParameters,
310
483
  ],
311
484
  };
312
485
  }
@@ -371,66 +544,8 @@ export class FlowInstrumentationService {
371
544
  const name = `RFLIB_Flow_Logger_${loggerId}`;
372
545
  // Create and truncate the label to ensure it's under 80 chars
373
546
  const label = this.truncateLabel(`Log Flow Invocation: ${flowName}`);
374
- // Verify name length
375
- if (name.length > 80) {
376
- // If still too long, use a simpler naming scheme (fallback)
377
- return {
378
- actionName: 'rflib_LoggerFlowAction',
379
- actionType: 'apex',
380
- name: `RFLIBLogger${loggerId}`,
381
- label,
382
- locationX: 176,
383
- locationY: 50,
384
- inputParameters: [
385
- {
386
- name: 'context',
387
- value: {
388
- stringValue: flowName,
389
- },
390
- },
391
- {
392
- name: 'logLevel',
393
- value: {
394
- stringValue: 'INFO',
395
- },
396
- },
397
- {
398
- name: 'message',
399
- value: {
400
- stringValue: `Flow ${flowName} started`,
401
- },
402
- },
403
- ],
404
- };
405
- }
406
- return {
407
- actionName: 'rflib_LoggerFlowAction',
408
- actionType: 'apex',
409
- name,
410
- label,
411
- locationX: 176,
412
- locationY: 50,
413
- inputParameters: [
414
- {
415
- name: 'context',
416
- value: {
417
- stringValue: flowName,
418
- },
419
- },
420
- {
421
- name: 'logLevel',
422
- value: {
423
- stringValue: 'INFO',
424
- },
425
- },
426
- {
427
- name: 'message',
428
- value: {
429
- stringValue: `Flow ${flowName} started`,
430
- },
431
- },
432
- ],
433
- };
547
+ // If still too long, use a simpler naming scheme (fallback)
548
+ return this.buildLoggerAction(name.length > 80 ? `RFLIBLogger${loggerId}` : name, label, flowName, 'INFO', `Flow ${flowName} started`);
434
549
  }
435
550
  // Helper to set CanvasMode to AUTO_LAYOUT_CANVAS for better flow layout
436
551
  static setCanvasMode(flowObj) {
@@ -501,6 +616,12 @@ export default class RflibLoggingFlowInstrument extends SfCommand {
501
616
  static description = messages.getMessage('description');
502
617
  static examples = messages.getMessages('examples');
503
618
  static flags = {
619
+ 'target-org': Flags.requiredOrg({
620
+ summary: messages.getMessage('flags.target-org.summary'),
621
+ description: messages.getMessage('flags.target-org.description'),
622
+ char: 'o',
623
+ required: true,
624
+ }),
504
625
  sourcepath: Flags.string({
505
626
  summary: messages.getMessage('flags.sourcepath.summary'),
506
627
  description: messages.getMessage('flags.sourcepath.description'),
@@ -518,6 +639,11 @@ export default class RflibLoggingFlowInstrument extends SfCommand {
518
639
  description: messages.getMessage('flags.skip-instrumented.description') || 'Do not instrument flows where RFLIB logging is already present',
519
640
  default: false,
520
641
  }),
642
+ 'skip-fault-paths': Flags.boolean({
643
+ summary: messages.getMessage('flags.skip-fault-paths.summary'),
644
+ description: messages.getMessage('flags.skip-fault-paths.description'),
645
+ default: false,
646
+ }),
521
647
  verbose: Flags.boolean({
522
648
  summary: messages.getMessage('flags.verbose.summary'),
523
649
  description: messages.getMessage('flags.verbose.description'),
@@ -549,15 +675,17 @@ export default class RflibLoggingFlowInstrument extends SfCommand {
549
675
  const sourcePath = flags.sourcepath;
550
676
  const isDryRun = flags.dryrun;
551
677
  const skipInstrumented = flags['skip-instrumented'];
678
+ const skipFaultPaths = flags['skip-fault-paths'] || !(await this.isFaultPathLoggingSupported(flags['target-org'].getConnection(undefined)));
552
679
  const isVerbose = flags.verbose;
553
680
  const excludePattern = flags.exclude;
554
681
  this.log(`Scanning Flow files in ${sourcePath} and sub directories`);
555
682
  this.logger.debug(`Dry run mode: ${isDryRun}`);
556
683
  this.logger.debug(`Skip instrumented: ${skipInstrumented}`);
684
+ this.logger.debug(`Skip fault paths: ${skipFaultPaths}`);
557
685
  this.spinner.start('Running...');
558
686
  const files = await this.findAllFlowFiles(sourcePath, excludePattern);
559
687
  await processWithConcurrency(files, flags.concurrency, async (filePath) => {
560
- await this.instrumentFlowFile(filePath, isDryRun, skipInstrumented, isVerbose);
688
+ await this.instrumentFlowFile(filePath, { isDryRun, skipInstrumented, skipFaultPaths, isVerbose });
561
689
  });
562
690
  this.spinner.stop();
563
691
  const duration = Date.now() - startTime;
@@ -567,12 +695,28 @@ export default class RflibLoggingFlowInstrument extends SfCommand {
567
695
  this.log(`Modified files: ${this.stats.modifiedFiles}`);
568
696
  return { ...this.stats };
569
697
  }
698
+ // Fault paths are only instrumented if the RFLIB package in the target org supports terminating the transaction
699
+ async isFaultPathLoggingSupported(conn) {
700
+ const minVersion = `${FAULT_PATH_MIN_RFLIB_VERSION.major}.${FAULT_PATH_MIN_RFLIB_VERSION.minor}.${FAULT_PATH_MIN_RFLIB_VERSION.patch}`;
701
+ const [rflib] = await getInstalledPackages(conn, [RFLIB_PACKAGE_NAME]);
702
+ if (!rflib) {
703
+ this.warn(messages.getMessage('warning.faultPaths.rflibNotInstalled', [minVersion]));
704
+ return false;
705
+ }
706
+ const installedVersion = formatVersion(rflib.version);
707
+ if (compareVersions(rflib.version, FAULT_PATH_MIN_RFLIB_VERSION) < 0) {
708
+ this.warn(messages.getMessage('warning.faultPaths.rflibOutdated', [installedVersion, minVersion]));
709
+ return false;
710
+ }
711
+ this.logger.debug(`RFLIB ${installedVersion} supports fault path logging`);
712
+ return true;
713
+ }
570
714
  async findAllFlowFiles(dirPath, excludePattern) {
571
715
  this.logger.debug(`Scanning directory: ${dirPath}`);
572
716
  const entries = await fs.promises.readdir(dirPath, { withFileTypes: true });
573
717
  const results = await Promise.all(entries.map(async (entry) => {
574
718
  const filePath = path.join(dirPath, entry.name);
575
- if (excludePattern && minimatch(filePath, excludePattern, { matchBase: true })) {
719
+ if (isExcluded(filePath, excludePattern)) {
576
720
  this.logger.debug(`Skipping excluded path: ${filePath}`);
577
721
  return [];
578
722
  }
@@ -586,7 +730,8 @@ export default class RflibLoggingFlowInstrument extends SfCommand {
586
730
  }));
587
731
  return results.flat();
588
732
  }
589
- async instrumentFlowFile(filePath, isDryRun, skipInstrumented, isVerbose) {
733
+ async instrumentFlowFile(filePath, options) {
734
+ const { isDryRun, skipInstrumented, skipFaultPaths, isVerbose } = options;
590
735
  const flowName = path.basename(filePath, '.flow-meta.xml');
591
736
  this.logger.debug(`Processing flow: ${flowName}`);
592
737
  try {
@@ -603,7 +748,7 @@ export default class RflibLoggingFlowInstrument extends SfCommand {
603
748
  this.logger.info(`Skipping already instrumented flow: ${flowName}`);
604
749
  return;
605
750
  }
606
- const instrumentedFlow = FlowInstrumentationService.instrumentFlow(flowObj, flowName, skipInstrumented);
751
+ const instrumentedFlow = FlowInstrumentationService.instrumentFlow(flowObj, flowName, skipInstrumented, skipFaultPaths);
607
752
  const newContent = FlowInstrumentationService.buildFlowContent(instrumentedFlow);
608
753
  if (content !== newContent) {
609
754
  this.stats.modifiedFiles++;