rflib-plugin 0.19.11 → 0.21.0

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.
@@ -1,5 +1,4 @@
1
1
  /* eslint-disable sf-plugin/only-extend-SfCommand */
2
- /* eslint-disable @typescript-eslint/return-await */
3
2
  /* eslint-disable @typescript-eslint/no-explicit-any */
4
3
  /* eslint-disable @typescript-eslint/no-unsafe-call */
5
4
  /* eslint-disable @typescript-eslint/no-unsafe-assignment */
@@ -12,8 +11,13 @@ import { SfCommand, Flags } from '@salesforce/sf-plugins-core';
12
11
  import * as xml2js from 'xml2js';
13
12
  import { minimatch } from 'minimatch';
14
13
  import { processWithConcurrency } from '../../../../shared/concurrency.js';
14
+ import { compareVersions, formatVersion, getInstalledPackages, } from '../../../../shared/packageClient.js';
15
15
  Messages.importMessagesDirectoryFromMetaUrl(import.meta.url);
16
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 };
17
21
  export class FlowInstrumentationService {
18
22
  static parser = new xml2js.Parser({
19
23
  explicitArray: false,
@@ -29,15 +33,52 @@ export class FlowInstrumentationService {
29
33
  newline: '\n'
30
34
  }
31
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;
32
73
  static async parseFlowContent(content) {
33
74
  try {
34
75
  return await this.parser.parseStringPromise(content);
35
76
  }
36
77
  catch (error) {
37
78
  if (error instanceof Error) {
38
- throw new Error(`Flow parsing failed: ${error.message}`);
79
+ throw new Error(`Flow parsing failed: ${error.message}`, { cause: error });
39
80
  }
40
- throw new Error('Flow parsing failed with unknown error');
81
+ throw new Error('Flow parsing failed with unknown error', { cause: error });
41
82
  }
42
83
  }
43
84
  static buildFlowContent(flowObj) {
@@ -64,9 +105,9 @@ export class FlowInstrumentationService {
64
105
  }
65
106
  catch (error) {
66
107
  if (error instanceof Error) {
67
- throw new Error(`Flow building failed: ${error.message}`);
108
+ throw new Error(`Flow building failed: ${error.message}`, { cause: error });
68
109
  }
69
- throw new Error('Flow building failed with unknown error');
110
+ throw new Error('Flow building failed with unknown error', { cause: error });
70
111
  }
71
112
  }
72
113
  // Helper to check if flow already contains RFLIB logger
@@ -77,10 +118,14 @@ export class FlowInstrumentationService {
77
118
  const actionCalls = Array.isArray(flowObj.Flow.actionCalls)
78
119
  ? flowObj.Flow.actionCalls
79
120
  : [flowObj.Flow.actionCalls];
80
- return actionCalls.some((action) => action.actionName === 'rflib:Logger' ||
81
- action.actionName === 'rflib_LoggerFlowAction' ||
82
- action.actionName === 'rflib_ApplicationEventLoggerAction' ||
83
- (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')));
84
129
  }
85
130
  // Helper to check if flow has a supported process type for instrumentation
86
131
  static isSupportedProcessType(flowObj) {
@@ -90,7 +135,7 @@ export class FlowInstrumentationService {
90
135
  (processType === 'AutoLaunchedFlow' && triggerType === 'RecordAfterSave');
91
136
  }
92
137
  // Main instrumentation function
93
- static instrumentFlow(flowObj, flowName, skipInstrumented = false) {
138
+ static instrumentFlow(flowObj, flowName, skipInstrumented = false, skipFaultPaths = false) {
94
139
  // Deep clone the object to avoid modifying the original
95
140
  const instrumentedFlow = JSON.parse(JSON.stringify(flowObj));
96
141
  // Skip if already instrumented and skipInstrumented flag is set
@@ -143,6 +188,10 @@ export class FlowInstrumentationService {
143
188
  if (instrumentedFlow.Flow.decisions) {
144
189
  this.instrumentDecisions(instrumentedFlow, flowName);
145
190
  }
191
+ // Log an error on every fault path of elements that can fail
192
+ if (!skipFaultPaths) {
193
+ this.instrumentFaultPaths(instrumentedFlow, flowName);
194
+ }
146
195
  // Reorder Flow properties
147
196
  const originalFlow = instrumentedFlow.Flow;
148
197
  const orderedFlow = {
@@ -177,21 +226,17 @@ export class FlowInstrumentationService {
177
226
  const decisionLabel = decision.label || decisionName;
178
227
  // Process default connector if it exists
179
228
  if (decision.defaultConnector?.targetReference) {
180
- const defaultTarget = decision.defaultConnector.targetReference;
181
229
  const defaultConnectorLabel = decision.defaultConnectorLabel || 'Default Outcome';
182
230
  // Create a logger for the default path
183
231
  const defaultLogger = this.createDecisionPathLogger(flowName, String(decisionName), String(decisionLabel), 'default', String(defaultConnectorLabel));
184
- // Connect logger to the original target
185
- defaultLogger.connector = {
186
- targetReference: defaultTarget
187
- };
232
+ // Move the original connector onto the logger so properties such as isGoTo
233
+ // stay on the edge that actually jumps to the original target
234
+ defaultLogger.connector = { ...decision.defaultConnector };
188
235
  // Add logger to actionCalls first, before updating the decision connector
189
236
  this.addActionCallToFlow(flowObj, defaultLogger);
190
- // Update the decision's default connector to point to our logger
237
+ // Point the decision's default connector at our logger with a plain connector
191
238
  // We're inside a forEach callback, so we have to modify the original object
192
- /* eslint-disable no-param-reassign */
193
- decision.defaultConnector.targetReference = defaultLogger.name;
194
- /* eslint-enable no-param-reassign */
239
+ decision.defaultConnector = { targetReference: defaultLogger.name };
195
240
  }
196
241
  // Process each rule if they exist
197
242
  if (decision.rules) {
@@ -202,22 +247,18 @@ export class FlowInstrumentationService {
202
247
  if (!rule.connector?.targetReference || !ruleNameRaw) {
203
248
  return;
204
249
  }
205
- const ruleTarget = rule.connector.targetReference;
206
250
  const ruleName = ruleNameRaw;
207
251
  const ruleLabel = rule.label || ruleName;
208
252
  // Create a logger for this rule outcome
209
253
  const ruleLogger = this.createDecisionPathLogger(flowName, String(decisionName), String(decisionLabel), String(ruleName), String(ruleLabel));
210
- // Connect logger to the original target
211
- ruleLogger.connector = {
212
- targetReference: ruleTarget
213
- };
254
+ // Move the original connector onto the logger so properties such as isGoTo
255
+ // stay on the edge that actually jumps to the original target
256
+ ruleLogger.connector = { ...rule.connector };
214
257
  // Add logger to actionCalls first, before updating the rule connector
215
258
  this.addActionCallToFlow(flowObj, ruleLogger);
216
- // Update the rule's connector to point to our logger
259
+ // Point the rule's connector at our logger with a plain connector
217
260
  // We're inside a forEach callback, so we have to modify the original object
218
- /* eslint-disable no-param-reassign */
219
- rule.connector.targetReference = ruleLogger.name;
220
- /* eslint-enable no-param-reassign */
261
+ rule.connector = { targetReference: ruleLogger.name };
221
262
  });
222
263
  }
223
264
  });
@@ -226,7 +267,6 @@ export class FlowInstrumentationService {
226
267
  // Note: This method does modify the parameter directly - we accepted the eslint warning
227
268
  // since we need to modify the flow object within callback functions where returning a new value isn't possible
228
269
  static addActionCallToFlow(flowObj, actionCall) {
229
- /* eslint-disable no-param-reassign */
230
270
  if (!flowObj.Flow.actionCalls) {
231
271
  flowObj.Flow.actionCalls = actionCall;
232
272
  }
@@ -238,7 +278,153 @@ export class FlowInstrumentationService {
238
278
  // If only one action exists, convert to array with new action first
239
279
  flowObj.Flow.actionCalls = [actionCall, flowObj.Flow.actionCalls];
240
280
  }
241
- /* eslint-enable no-param-reassign */
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];
242
428
  }
243
429
  // Helper to create a logging action for decision paths
244
430
  static createDecisionPathLogger(flowName, decisionName, decisionLabel, outcomeName, outcomeLabel) {
@@ -261,37 +447,12 @@ export class FlowInstrumentationService {
261
447
  const name = `RFLIB_Flow_Logger_Decision_${sanitizedDecisionName}_${sanitizedOutcomeName}_${loggerId}`;
262
448
  // Create and truncate the label to ensure it's under 80 chars
263
449
  const label = this.truncateLabel(`Log Decision: ${decisionLabelStr} - ${outcomeLabelStr}`);
450
+ const message = `Decision '${decisionLabelStr}' outcome: ${outcomeLabelStr}`;
264
451
  // Fallback if still too long
265
- if (name.length > 80) {
266
- return {
267
- actionName: 'rflib_LoggerFlowAction',
268
- actionType: 'apex',
269
- name: `RFLIBLogDec${loggerId}`,
270
- label,
271
- locationX: 176,
272
- locationY: 50,
273
- inputParameters: [
274
- {
275
- name: 'context',
276
- value: {
277
- stringValue: flowName,
278
- },
279
- },
280
- {
281
- name: 'logLevel',
282
- value: {
283
- stringValue: 'INFO',
284
- },
285
- },
286
- {
287
- name: 'message',
288
- value: {
289
- stringValue: `Decision '${decisionLabelStr}' outcome: ${outcomeLabelStr}`,
290
- },
291
- },
292
- ],
293
- };
294
- }
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 = []) {
295
456
  return {
296
457
  actionName: 'rflib_LoggerFlowAction',
297
458
  actionType: 'apex',
@@ -303,21 +464,22 @@ export class FlowInstrumentationService {
303
464
  {
304
465
  name: 'context',
305
466
  value: {
306
- stringValue: flowName,
467
+ stringValue: context,
307
468
  },
308
469
  },
309
470
  {
310
471
  name: 'logLevel',
311
472
  value: {
312
- stringValue: 'INFO',
473
+ stringValue: logLevel,
313
474
  },
314
475
  },
315
476
  {
316
477
  name: 'message',
317
478
  value: {
318
- stringValue: `Decision '${decisionLabelStr}' outcome: ${outcomeLabelStr}`,
479
+ stringValue: message,
319
480
  },
320
481
  },
482
+ ...additionalParameters,
321
483
  ],
322
484
  };
323
485
  }
@@ -382,66 +544,8 @@ export class FlowInstrumentationService {
382
544
  const name = `RFLIB_Flow_Logger_${loggerId}`;
383
545
  // Create and truncate the label to ensure it's under 80 chars
384
546
  const label = this.truncateLabel(`Log Flow Invocation: ${flowName}`);
385
- // Verify name length
386
- if (name.length > 80) {
387
- // If still too long, use a simpler naming scheme (fallback)
388
- return {
389
- actionName: 'rflib_LoggerFlowAction',
390
- actionType: 'apex',
391
- name: `RFLIBLogger${loggerId}`,
392
- label,
393
- locationX: 176,
394
- locationY: 50,
395
- inputParameters: [
396
- {
397
- name: 'context',
398
- value: {
399
- stringValue: flowName,
400
- },
401
- },
402
- {
403
- name: 'logLevel',
404
- value: {
405
- stringValue: 'INFO',
406
- },
407
- },
408
- {
409
- name: 'message',
410
- value: {
411
- stringValue: `Flow ${flowName} started`,
412
- },
413
- },
414
- ],
415
- };
416
- }
417
- return {
418
- actionName: 'rflib_LoggerFlowAction',
419
- actionType: 'apex',
420
- name,
421
- label,
422
- locationX: 176,
423
- locationY: 50,
424
- inputParameters: [
425
- {
426
- name: 'context',
427
- value: {
428
- stringValue: flowName,
429
- },
430
- },
431
- {
432
- name: 'logLevel',
433
- value: {
434
- stringValue: 'INFO',
435
- },
436
- },
437
- {
438
- name: 'message',
439
- value: {
440
- stringValue: `Flow ${flowName} started`,
441
- },
442
- },
443
- ],
444
- };
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`);
445
549
  }
446
550
  // Helper to set CanvasMode to AUTO_LAYOUT_CANVAS for better flow layout
447
551
  static setCanvasMode(flowObj) {
@@ -482,9 +586,7 @@ export class FlowInstrumentationService {
482
586
  metadataValues[canvasModeIndex].value.stringValue = 'AUTO_LAYOUT_CANVAS';
483
587
  }
484
588
  // Assign back the potentially modified array
485
- /* eslint-disable no-param-reassign */
486
589
  flowObj.Flow.processMetadataValues = metadataValues;
487
- /* eslint-enable no-param-reassign */
488
590
  }
489
591
  // Helper to add variable references to the logging message when available
490
592
  static enhanceLoggingWithVariables(loggingAction, flowObj) {
@@ -514,6 +616,12 @@ export default class RflibLoggingFlowInstrument extends SfCommand {
514
616
  static description = messages.getMessage('description');
515
617
  static examples = messages.getMessages('examples');
516
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
+ }),
517
625
  sourcepath: Flags.string({
518
626
  summary: messages.getMessage('flags.sourcepath.summary'),
519
627
  description: messages.getMessage('flags.sourcepath.description'),
@@ -531,6 +639,11 @@ export default class RflibLoggingFlowInstrument extends SfCommand {
531
639
  description: messages.getMessage('flags.skip-instrumented.description') || 'Do not instrument flows where RFLIB logging is already present',
532
640
  default: false,
533
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
+ }),
534
647
  verbose: Flags.boolean({
535
648
  summary: messages.getMessage('flags.verbose.summary'),
536
649
  description: messages.getMessage('flags.verbose.description'),
@@ -562,15 +675,17 @@ export default class RflibLoggingFlowInstrument extends SfCommand {
562
675
  const sourcePath = flags.sourcepath;
563
676
  const isDryRun = flags.dryrun;
564
677
  const skipInstrumented = flags['skip-instrumented'];
678
+ const skipFaultPaths = flags['skip-fault-paths'] || !(await this.isFaultPathLoggingSupported(flags['target-org'].getConnection(undefined)));
565
679
  const isVerbose = flags.verbose;
566
680
  const excludePattern = flags.exclude;
567
681
  this.log(`Scanning Flow files in ${sourcePath} and sub directories`);
568
682
  this.logger.debug(`Dry run mode: ${isDryRun}`);
569
683
  this.logger.debug(`Skip instrumented: ${skipInstrumented}`);
684
+ this.logger.debug(`Skip fault paths: ${skipFaultPaths}`);
570
685
  this.spinner.start('Running...');
571
686
  const files = await this.findAllFlowFiles(sourcePath, excludePattern);
572
687
  await processWithConcurrency(files, flags.concurrency, async (filePath) => {
573
- await this.instrumentFlowFile(filePath, isDryRun, skipInstrumented, isVerbose);
688
+ await this.instrumentFlowFile(filePath, { isDryRun, skipInstrumented, skipFaultPaths, isVerbose });
574
689
  });
575
690
  this.spinner.stop();
576
691
  const duration = Date.now() - startTime;
@@ -580,6 +695,22 @@ export default class RflibLoggingFlowInstrument extends SfCommand {
580
695
  this.log(`Modified files: ${this.stats.modifiedFiles}`);
581
696
  return { ...this.stats };
582
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
+ }
583
714
  async findAllFlowFiles(dirPath, excludePattern) {
584
715
  this.logger.debug(`Scanning directory: ${dirPath}`);
585
716
  const entries = await fs.promises.readdir(dirPath, { withFileTypes: true });
@@ -599,7 +730,8 @@ export default class RflibLoggingFlowInstrument extends SfCommand {
599
730
  }));
600
731
  return results.flat();
601
732
  }
602
- async instrumentFlowFile(filePath, isDryRun, skipInstrumented, isVerbose) {
733
+ async instrumentFlowFile(filePath, options) {
734
+ const { isDryRun, skipInstrumented, skipFaultPaths, isVerbose } = options;
603
735
  const flowName = path.basename(filePath, '.flow-meta.xml');
604
736
  this.logger.debug(`Processing flow: ${flowName}`);
605
737
  try {
@@ -616,7 +748,7 @@ export default class RflibLoggingFlowInstrument extends SfCommand {
616
748
  this.logger.info(`Skipping already instrumented flow: ${flowName}`);
617
749
  return;
618
750
  }
619
- const instrumentedFlow = FlowInstrumentationService.instrumentFlow(flowObj, flowName, skipInstrumented);
751
+ const instrumentedFlow = FlowInstrumentationService.instrumentFlow(flowObj, flowName, skipInstrumented, skipFaultPaths);
620
752
  const newContent = FlowInstrumentationService.buildFlowContent(instrumentedFlow);
621
753
  if (content !== newContent) {
622
754
  this.stats.modifiedFiles++;