@jacebenson/jsn 5.5.1-dev.157.1 → 5.5.1-dev.159.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.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/src/flow-create.js +631 -27
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jacebenson/jsn",
3
- "version": "5.5.1-dev.157.1",
3
+ "version": "5.5.1-dev.159.1",
4
4
  "description": "A command-line interface for ServiceNow that follows the Unix philosophy: simple, composable, and scriptable.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -160,6 +160,8 @@ export function validateFlowManifest(manifest) {
160
160
  if (manifest.variables !== undefined || manifest.flowVariables !== undefined) throw new Error('Flow-variable lifecycle is unsupported in this creation slice');
161
161
  if (manifest.errorHandling !== undefined) throw new Error('Error handling is unsupported in this creation slice');
162
162
  if (manifest.stages !== undefined) validateStages(manifest.stages);
163
+ if (manifest.stageTemplate !== undefined && !String(manifest.stageTemplate).trim()) throw new Error('Flow manifest stageTemplate must not be empty');
164
+ if (manifest.stageSet !== undefined && !String(manifest.stageSet).trim()) throw new Error('Flow manifest stageSet must not be empty');
163
165
  const trigger = manifest.trigger;
164
166
  if (!trigger || typeof trigger !== 'object' || Array.isArray(trigger)) throw new Error('Flow manifest requires a trigger object');
165
167
  for (const key of Object.keys(trigger)) if (!['type', 'table', 'condition', 'inputs'].includes(key)) throw new Error(`Flow manifest trigger field "${key}" is unsupported`);
@@ -243,6 +245,81 @@ function stageValueFromLabel(label) {
243
245
  * `stageId` is only meaningful for updates: an entry without one inserts a new
244
246
  * stage, an entry with one edits the stage it names.
245
247
  */
248
+
249
+ export async function resolveStageTemplate(sdk, templateIdentifier) {
250
+ const ident = String(templateIdentifier || "").trim();
251
+ if (!ident) throw new Error('Stage template identifier must not be empty');
252
+ // The identifier is embedded in an encoded query, so a separator character
253
+ // would silently change which records match.
254
+ if (/[\^=\n\r]/.test(ident)) throw new Error(`Stage template "${ident}" contains a query separator (^ or =); pass a plain name or sys_id`);
255
+ // 1. Check if ident matches a stage_set sys_id or name
256
+ let setId = "";
257
+ if (/^[0-9a-fA-F]{32}$/.test(ident)) {
258
+ setId = ident;
259
+ } else {
260
+ // Resolve by table first, then by stage set name. Provider failures must
261
+ // surface: a swallowed 401 would read as "template not found".
262
+ const tableMatches = await sdk.list("stage_set_table", new URLSearchParams({
263
+ sysparm_query: `table=${ident}^ORset.nameLIKE${ident}`,
264
+ sysparm_limit: "1"
265
+ }));
266
+ if (tableMatches.length && tableMatches[0].set) {
267
+ setId = typeof tableMatches[0].set === "object" ? tableMatches[0].set.value : tableMatches[0].set;
268
+ } else {
269
+ const setMatches = await sdk.list("stage_set", new URLSearchParams({
270
+ sysparm_query: `nameLIKE${ident}`,
271
+ sysparm_limit: "1"
272
+ }));
273
+ if (setMatches.length) setId = setMatches[0].sys_id;
274
+ }
275
+ }
276
+ if (!setId) throw new Error(`Stage template "${ident}" not found in stage_set or stage_set_table`);
277
+
278
+ // 2. Fetch stage_set_entry records for setId
279
+ const entries = await sdk.list("stage_set_entry", new URLSearchParams({
280
+ sysparm_query: `set=${setId}`,
281
+ sysparm_display_value: "all"
282
+ }));
283
+ if (!entries.length) throw new Error(`No stage entries found for stage template "${ident}" (${setId})`);
284
+
285
+ // Sort: Request Cancelled & Completed system stages, or order-based
286
+ const mapped = entries.map(e => {
287
+ const label = e.name?.display_value || e.name?.value || e.name || "";
288
+ const value = e.value?.display_value || e.value?.value || e.value || stageValueFromLabel(label);
289
+ const duration = e.ola?.value || e.ola?.display_value || STAGE_DURATION;
290
+ // `order` comes back display-formatted ("1,000"), so parseInt alone reads 1.
291
+ const rawOrder = String(e.order?.value ?? e.order ?? "0").replace(/[^0-9-]/g, "");
292
+ const orderNum = Number.isFinite(parseInt(rawOrder, 10)) ? parseInt(rawOrder, 10) : 0;
293
+ return {
294
+ label,
295
+ value,
296
+ duration,
297
+ rawOrder: orderNum,
298
+ system: (label === "Request Cancelled" || label === "Completed" || value === "complete" || value === "Request Cancelled")
299
+ };
300
+ });
301
+
302
+ // Flow Designer sorts Request Cancelled (order 0, system: true), Completed (order 1, system: true), then non-system stages by rawOrder
303
+ const systemStages = mapped.filter(s => s.system).sort((a, b) => {
304
+ if (a.value === "Request Cancelled" || a.label === "Request Cancelled") return -1;
305
+ if (b.value === "Request Cancelled" || b.label === "Request Cancelled") return 1;
306
+ return a.rawOrder - b.rawOrder;
307
+ });
308
+ const normalStages = mapped.filter(s => !s.system).sort((a, b) => a.rawOrder - b.rawOrder);
309
+
310
+ const finalStages = [...systemStages, ...normalStages].map((s, idx) => ({
311
+ label: s.label,
312
+ value: s.value,
313
+ duration: s.duration,
314
+ order: idx,
315
+ system: s.system,
316
+ alwaysShow: true,
317
+ componentIndexes: []
318
+ }));
319
+
320
+ return finalStages;
321
+ }
322
+
246
323
  export function validateStages(stages, { update = false } = {}) {
247
324
  if (!Array.isArray(stages)) throw new Error('Flow stages must be an array');
248
325
  for (const [index, stage] of stages.entries()) {
@@ -379,17 +456,95 @@ export function buildFlowPatchMutation({ flowId, trigger, actions }) {
379
456
  return `mutation { global { snFlowDesigner { flow(${patch}) { triggerInstances { inserts { sysId } updates } actions { inserts { sysId uiUniqueIdentifier } } } } } }`;
380
457
  }
381
458
 
382
- export function buildFlowUpdateMutation({ flowId, triggerUpdates = [], actionUpdates = [], stageInserts = [], stageUpdates = [] }) {
459
+
460
+ const FLOW_LOGIC_DEFINITIONS = {
461
+ 'if': {
462
+ id: 'af4e1945c3e232002841b63b12d3ae3e',
463
+ name: 'If',
464
+ type: 'IF',
465
+ description: 'Selectively apply one or more actions only when a list of conditions is met.',
466
+ compilationClass: 'com.glide.flow.compiler.logic_block.IfCompiler',
467
+ order: 1,
468
+ connectedTo: '',
469
+ attributes: 'allow_children=true,allow_siblings=true,icon_class=diamond-if-icon,line_type=q_if_curve,pills_draggable_outside_block=false,',
470
+ },
471
+ 'else if': {
472
+ id: '666e5545c3e232002841b63b12d3ae99',
473
+ name: 'Else If',
474
+ type: 'ELSEIF',
475
+ description: 'Selectively apply one or more actions only when a list of conditions is met.',
476
+ compilationClass: 'com.glide.flow.compiler.logic_block.ElseIfCompiler',
477
+ order: 2,
478
+ connectedTo: 'af4e1945c3e232002841b63b12d3ae3e,666e5545c3e232002841b63b12d3ae99',
479
+ attributes: 'allow_children=true,allow_siblings=true,icon_class=elseif-icon,line_type=q_if_curve,pills_draggable_outside_block=false,',
480
+ },
481
+ 'else': {
482
+ id: '1f781bf3c32232002841b63b12d3aee6',
483
+ name: 'Else',
484
+ type: 'ELSE',
485
+ description: 'Else statement',
486
+ compilationClass: 'com.glide.flow.compiler.logic_block.ElseCompiler',
487
+ order: 3,
488
+ connectedTo: '666e5545c3e232002841b63b12d3ae99,af4e1945c3e232002841b63b12d3ae3e',
489
+ attributes: 'allow_children=true,allow_siblings=true,disable_opening=true,icon_class=else-icon,line_type=q_if_curve,pills_draggable_outside_block=false,',
490
+ },
491
+ 'set flow variables': {
492
+ id: '4f787d1e0f9b0010ecf0cc52ff767ea0',
493
+ name: 'Set Flow Variables',
494
+ type: 'SETFLOWVARIABLES',
495
+ description: "Assign a value to one or more flow variables. Change or update a variable's value during a flow.",
496
+ compilationClass: 'com.glide.flow.compiler.logic_block.SetVariablesCompiler',
497
+ order: 14,
498
+ connectedTo: '',
499
+ attributes: 'allow_children=false,allow_siblings=true,',
500
+ },
501
+ 'end flow': {
502
+ id: 'd176605ea76103004f27b0d2187901c7',
503
+ name: 'End Flow',
504
+ type: 'END',
505
+ description: 'Use this flow logic to stop a flow within flow designer.',
506
+ compilationClass: 'com.glide.flow.compiler.logic_block.EndCompiler',
507
+ order: 10,
508
+ connectedTo: '',
509
+ attributes: 'allow_children=false,allow_siblings=false,disable_opening=true,',
510
+ }
511
+ };
512
+
513
+ export function buildFlowUpdateMutation({ flowId, triggerUpdates = [], actionUpdates = [], actionInserts = [], actionDeletes = [], flowVariableInserts = [], flowLogicInserts = [], flowLogicUpdates = [], flowLogicDeletes = [], labelCacheUpdates = [], labelCacheInserts = [], stageInserts = [], stageUpdates = [] }) {
383
514
  const updates = [];
384
515
  if (triggerUpdates.length) updates.push(`triggerInstances: {update: [${triggerUpdates.map(gqlInputObject).join(', ')}]}`);
385
- if (actionUpdates.length) updates.push(`actions: {update: [${actionUpdates.map(gqlInputObject).join(', ')}]}`);
516
+ const actionParts = [];
517
+ if (actionInserts.length) actionParts.push(`insert: [${actionInserts.map(gqlInputObject).join(', ')}]`);
518
+ if (actionUpdates.length) actionParts.push(`update: [${actionUpdates.map(gqlInputObject).join(', ')}]`);
519
+ if (actionDeletes.length) actionParts.push(`delete: [${actionDeletes.map(id => gqlString(id)).join(', ')}]`);
520
+ if (actionParts.length) updates.push(`actions: {${actionParts.join(', ')}}`);
521
+ if (flowVariableInserts.length) updates.push(`flowVariables: {insert: [${flowVariableInserts.map(gqlInputObject).join(', ')}]}`);
522
+ const logicParts = [];
523
+ if (flowLogicInserts.length) logicParts.push(`insert: [${flowLogicInserts.map(gqlInputObject).join(', ')}]`);
524
+ if (flowLogicUpdates.length) logicParts.push(`update: [${flowLogicUpdates.map(gqlInputObject).join(', ')}]`);
525
+ if (flowLogicDeletes.length) logicParts.push(`delete: [${flowLogicDeletes.map(id => gqlString(id)).join(', ')}]`);
526
+ if (logicParts.length) updates.push(`flowLogics: {${logicParts.join(', ')}}`);
527
+ const labelParts = [];
528
+ if (labelCacheInserts.length) labelParts.push(`insert: [${labelCacheInserts.map(gqlInputObject).join(', ')}]`);
529
+ if (labelCacheUpdates.length) labelParts.push(`update: [${labelCacheUpdates.map(gqlInputObject).join(', ')}]`);
530
+ if (labelParts.length) updates.push(`labelCache: {${labelParts.join(', ')}}`);
386
531
  const stageParts = [];
387
- if (stageInserts.length) stageParts.push(`insert: [${stageInserts.map(gqlInputObject).join(', ')}]`);
532
+ if (stageInserts.length) stageParts.push(`insert: [${stageInserts.map(s => {
533
+ const copy = { ...s };
534
+ delete copy.system;
535
+ return gqlInputObject(copy);
536
+ }).join(', ')}]`);
388
537
  if (stageUpdates.length) stageParts.push(`update: [${stageUpdates.map(gqlInputObject).join(', ')}]`);
389
538
  if (stageParts.length) updates.push(`stages: {${stageParts.join(', ')}}`);
390
539
  if (!updates.length) throw new Error('Flow update mutation requires at least one change');
391
540
  const patch = `flowPatch: {flowId: ${gqlString(flowId)}, ${updates.join(', ')}}`;
392
- return `mutation { global { snFlowDesigner { flow(${patch}) { triggerInstances { updates } actions { updates } stages { inserts { sysId } } } } } }`;
541
+ const returnFields = ['triggerInstances { updates }'];
542
+ if (actionInserts.length) returnFields.push('actions { inserts { sysId uiUniqueIdentifier } updates }');
543
+ else returnFields.push('actions { updates }');
544
+ if (flowLogicInserts.length) returnFields.push('flowLogics { inserts { sysId uiUniqueIdentifier } }');
545
+ if (flowVariableInserts.length) returnFields.push('flowVariables { inserts { sysId uiUniqueIdentifier } }');
546
+ returnFields.push('stages { inserts { sysId } }');
547
+ return `mutation { global { snFlowDesigner { flow(${patch}) { ${returnFields.join(' ')} } } } }`;
393
548
  }
394
549
 
395
550
  export async function readProcessFlow(sdk, instance, flowId, scope) {
@@ -735,8 +890,8 @@ async function resolveExistingAction(sdk, actions, requested, index) {
735
890
 
736
891
  export function validateFlowUpdateManifest(manifest) {
737
892
  if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) throw new Error('Flow update manifest must be a JSON object');
738
- const allowed = new Set(['scope', 'trigger', 'actions', 'stages']);
739
- for (const key of Object.keys(manifest)) if (!allowed.has(key)) throw new Error(`Flow update field "${key}" is unsupported; only trigger, existing action inputs and stages may be updated`);
893
+ const allowed = new Set(['scope', 'trigger', 'actions', 'stages', 'stageTemplate', 'stageSet', 'flowVariables', 'variables', 'flowLogics', 'logic', 'deleteSteps', 'delete', 'deleteOrders']);
894
+ for (const key of Object.keys(manifest)) if (!allowed.has(key)) throw new Error(`Flow update field "${key}" is unsupported; editable: trigger, action inputs, action inserts, step deletes, flow variables, flow logic, stage placement`);
740
895
  if (manifest.scope !== undefined && !String(manifest.scope).trim()) throw new Error('Flow update scope must not be empty');
741
896
  if (manifest.trigger !== undefined) {
742
897
  if (!manifest.trigger || typeof manifest.trigger !== 'object' || Array.isArray(manifest.trigger)) throw new Error('Flow update trigger must be an object');
@@ -757,8 +912,15 @@ export function validateFlowUpdateManifest(manifest) {
757
912
  if (Object.keys(action.inputs).length === 0) throw new Error(`Update action ${index + 1} inputs must contain at least one changed value`);
758
913
  }
759
914
  }
760
- if (manifest.trigger === undefined && manifest.actions === undefined && manifest.stages === undefined) throw new Error('Flow update manifest must specify trigger, actions and/or stages');
915
+ if (manifest.trigger === undefined && manifest.actions === undefined && manifest.stages === undefined && manifest.stageTemplate === undefined && manifest.stageSet === undefined && manifest.flowVariables === undefined && manifest.variables === undefined && manifest.flowLogics === undefined && manifest.logic === undefined && manifest.deleteSteps === undefined && manifest.delete === undefined && manifest.deleteOrders === undefined) throw new Error('Flow update manifest must specify trigger, actions and/or stages');
761
916
  if (manifest.stages !== undefined) validateStages(manifest.stages, { update: true });
917
+ for (const key of ['stageTemplate', 'stageSet']) {
918
+ if (manifest[key] === undefined) continue;
919
+ if (typeof manifest[key] !== 'string' || !manifest[key].trim()) throw new Error(`Flow update ${key} must be a non-empty string`);
920
+ }
921
+ if (manifest.stages !== undefined && (manifest.stageTemplate !== undefined || manifest.stageSet !== undefined)) {
922
+ throw new Error('Flow update takes stages or a stage template, not both; rename the stage entries to change them');
923
+ }
762
924
  return manifest;
763
925
  }
764
926
 
@@ -1138,7 +1300,11 @@ export async function createFlowFromManifest(sdk, instance, inputManifest, optio
1138
1300
 
1139
1301
  // Stages carry componentIndexes that name flow-step orders, so placement
1140
1302
  // runs after the actions exist — the same order Flow Designer uses.
1141
- const stageInserts = buildStageInserts(manifest.stages || [], { idFactory, flowId });
1303
+ let manifestStages = manifest.stages || [];
1304
+ if ((manifest.stageTemplate || manifest.stageSet) && manifestStages.length === 0) {
1305
+ manifestStages = await resolveStageTemplate(sdk, manifest.stageTemplate || manifest.stageSet);
1306
+ }
1307
+ const stageInserts = buildStageInserts(manifestStages, { idFactory, flowId });
1142
1308
  if (stageInserts.length) {
1143
1309
  const stageResponse = await mutationContext('stage_placement', readUpdateSet, snapshots, () => sdk.request(`${instance}${GRAPHQL_ENDPOINT}`, {
1144
1310
  method: 'POST',
@@ -1177,6 +1343,96 @@ export async function createFlowFromManifest(sdk, instance, inputManifest, optio
1177
1343
  }
1178
1344
  }
1179
1345
 
1346
+ // Flow Designer renders a canvas pill from the `label` of its label_cache entry;
1347
+ // the ProcessFlow read exposes that cache as `labelCacheAsJsonString` (a JSON
1348
+ // string), never as a `label_cache` array. Reading the wrong field is how a
1349
+ // write ends up with an entry that has a name and no label to draw.
1350
+ function normalizeUsedInstances(used) {
1351
+ const out = new Map();
1352
+ const add = (uiId, inputName) => {
1353
+ if (!uiId || !inputName) return;
1354
+ if (!out.has(uiId)) out.set(uiId, []);
1355
+ const names = out.get(uiId);
1356
+ if (!names.includes(inputName)) names.push(inputName);
1357
+ };
1358
+ if (Array.isArray(used)) {
1359
+ for (const entry of used) add(stringValue(entry?.uiUniqueIdentifier), stringValue(entry?.inputName));
1360
+ } else if (used && typeof used === 'object') {
1361
+ for (const [uiId, names] of Object.entries(used)) {
1362
+ for (const name of (Array.isArray(names) ? names : [names])) add(uiId, stringValue(name));
1363
+ }
1364
+ }
1365
+ const result = {};
1366
+ for (const [uiId, names] of out) result[uiId] = names;
1367
+ return result;
1368
+ }
1369
+
1370
+ export function readLabelCache(definition) {
1371
+ const raw = definition?.labelCacheAsJsonString ?? definition?.label_cache ?? definition?.labelCache;
1372
+ let entries = raw;
1373
+ if (typeof raw === 'string') {
1374
+ try { entries = raw.trim() ? JSON.parse(raw) : []; } catch { entries = []; }
1375
+ }
1376
+ if (!Array.isArray(entries)) return [];
1377
+ return entries
1378
+ .map(entry => ({
1379
+ name: stringValue(entry?.name),
1380
+ label: stringValue(entry?.label),
1381
+ type: stringValue(entry?.type),
1382
+ baseType: stringValue(entry?.base_type || entry?.baseType),
1383
+ usedInstances: normalizeUsedInstances(entry?.usedInstances),
1384
+ }))
1385
+ .filter(entry => entry.name);
1386
+ }
1387
+
1388
+ function describeKnownPills(cache) {
1389
+ const names = cache.map(entry => entry.name);
1390
+ if (!names.length) return 'this flow has no registered data pills';
1391
+ return `registered pills: ${names.slice(0, 8).join(', ')}${names.length > 8 ? ` (+${names.length - 8} more)` : ''}`;
1392
+ }
1393
+
1394
+ // A pill no entry covers still needs a label the canvas can draw. Resolve the
1395
+ // producing step and the field it names, then build the label Flow Designer
1396
+ // itself would: `Trigger - <trigger>➛<input>` or `<order> - <action>➛<input>`.
1397
+ // `pending` covers steps this same manifest is inserting: their identity and
1398
+ // input schema already exist here even though the flow does not carry them yet.
1399
+ export function resolvePillBinding(definition, pillName, flowId, cache, pending = []) {
1400
+ const fail = () => {
1401
+ throw new Error(`Flow ${flowId} has no label_cache entry for data pill {{${pillName}}}; ${describeKnownPills(cache)}. Use a pill this flow already registers, or resave the flow in Flow Designer first. No content write attempted.`);
1402
+ };
1403
+ const separator = pillName.indexOf('.');
1404
+ if (separator <= 0) return fail();
1405
+ const stepKey = pillName.slice(0, separator);
1406
+ const fieldName = pillName.slice(separator + 1).split('.')[0];
1407
+ const describe = (fields, name) => {
1408
+ const field = inputList({ inputs: fields }).find(entry => stringValue(entry?.name) === name);
1409
+ if (!field) return null;
1410
+ return {
1411
+ label: stringValue(field?.parameter?.label) || stringValue(field?.parameter?.name) || String(field?.name ?? ''),
1412
+ type: stringValue(field?.parameter?.type),
1413
+ };
1414
+ };
1415
+
1416
+ const candidates = [
1417
+ ...findArray(definition, 'triggerInstances').map(step => ({ ...step, trigger: true })),
1418
+ ...findExistingActions(definition).map(step => ({ ...step, trigger: false })),
1419
+ ...pending.map(step => ({ ...step, trigger: false })),
1420
+ ];
1421
+ for (const step of candidates) {
1422
+ const name = stringValue(step.name);
1423
+ const order = stringValue(step.order) || '1';
1424
+ const uiId = stringValue(step.uiUniqueIdentifier || step.ui_unique_identifier);
1425
+ const matchesAlias = new RegExp(`^${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}_\\d+$`).test(stepKey);
1426
+ if (!matchesAlias && stepKey !== uiId) continue;
1427
+ // Inputs and outputs both become draggable pills; look at each before failing.
1428
+ const field = describe(step.inputs, fieldName) || describe(step.outputs, fieldName);
1429
+ if (!field) continue;
1430
+ const prefix = step.trigger ? `Trigger - ${name}` : `${order} - ${name}`;
1431
+ return { label: `${prefix}➛${field.label}`, type: field.type };
1432
+ }
1433
+ return fail();
1434
+ }
1435
+
1180
1436
  export async function updateFlowFromManifest(sdk, instance, identifier, inputManifest, options = {}) {
1181
1437
  const manifest = validateFlowUpdateManifest(inputManifest);
1182
1438
  const target = await resolveFlowForUpdate(sdk, identifier);
@@ -1212,7 +1468,19 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1212
1468
  const snapshots = [];
1213
1469
  const triggerUpdates = [];
1214
1470
  const actionUpdates = [];
1215
- const stageInserts = buildStageInserts((manifest.stages || []).filter(stage => stage.stageId === undefined), { idFactory: options.idFactory || (() => randomUUID()), flowId });
1471
+ const actionInserts = [];
1472
+ const actionDeletes = [];
1473
+ const flowVariableInserts = [];
1474
+ const flowLogicInserts = [];
1475
+ const flowLogicUpdates = [];
1476
+ const flowLogicDeletes = [];
1477
+ const labelCacheUpdates = [];
1478
+ let manifestStages = manifest.stages || [];
1479
+ if ((manifest.stageTemplate || manifest.stageSet) && manifestStages.length === 0) {
1480
+ const templateStages = await resolveStageTemplate(sdk, manifest.stageTemplate || manifest.stageSet);
1481
+ manifestStages = templateStages;
1482
+ }
1483
+ const stageInserts = buildStageInserts(manifestStages.filter(stage => stage.stageId === undefined), { idFactory: options.idFactory || (() => randomUUID()), flowId });
1216
1484
  const stageUpdates = buildStageUpdates((manifest.stages || []).filter(stage => stage.stageId !== undefined));
1217
1485
  const changedActionInputs = new Map();
1218
1486
  const actionTargets = new Map();
@@ -1231,18 +1499,83 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1231
1499
  }
1232
1500
  }
1233
1501
  const existingActions = findExistingActions(beforeDefinition);
1502
+ const existingOrders = new Set(existingActions.map(a => String(a.order)));
1503
+ const idFactory = options.idFactory || (() => randomUUID());
1504
+ const pillToInstances = new Map();
1505
+ const pendingSteps = [];
1506
+ const actionUiMap = new Map();
1507
+ for (const a of existingActions) {
1508
+ const ui = stringValue(a.uiUniqueIdentifier || a.ui_unique_identifier);
1509
+ if (a.order && ui) actionUiMap.set(String(a.order), ui);
1510
+ }
1511
+ // One input value can carry several pills; register every reference, not just
1512
+ // the first, or the later ones never reach label_cache and stay blank.
1513
+ const collectPills = (value, uiUniqueIdentifier, inputName) => {
1514
+ for (const match of String(value).matchAll(/\{\{([^}]+)\}\}/g)) {
1515
+ const pillName = match[1].trim();
1516
+ if (!pillName) continue;
1517
+ if (!pillToInstances.has(pillName)) pillToInstances.set(pillName, []);
1518
+ const instances = pillToInstances.get(pillName);
1519
+ if (!instances.some(entry => entry.uiUniqueIdentifier === uiUniqueIdentifier && entry.inputName === inputName)) {
1520
+ instances.push({ uiUniqueIdentifier, inputName });
1521
+ }
1522
+ }
1523
+ };
1524
+
1234
1525
  for (const [index, requested] of (manifest.actions || []).entries()) {
1235
- const existing = await resolveExistingAction(sdk, existingActions, requested, index);
1236
- const update = buildActionUpdate(existing, requested, index);
1237
- actionUpdates.push(update);
1238
- const uiId = stringValue(existing.uiUniqueIdentifier || existing.ui_unique_identifier);
1239
- if (actionTargets.has(uiId)) throw new Error(`Duplicate action update for order ${requested.order}; combine input changes in one action entry`);
1240
- actionTargets.set(uiId, existing);
1241
- changedActionInputs.set(uiId, new Set(Object.keys(requested.inputs)));
1242
- for (const [input, after] of Object.entries(requested.inputs)) changes.push({ component: 'action', order: requested.order, type: requested.type, input, before: inputRawValue(inputList(existing).find(field => field.name === input)), after });
1526
+ const isInsert = !existingOrders.has(String(requested.order));
1527
+ if (isInsert) {
1528
+ const resolved = await resolveActionType(sdk, requested.type);
1529
+ const actionDefinition = await readActionDefinition(sdk, instance, resolved.id, scope);
1530
+ const uiUniqueIdentifier = requested.uiUniqueIdentifier || idFactory();
1531
+ actionUiMap.set(String(requested.order), uiUniqueIdentifier);
1532
+ const insertInputs = buildTypedInputs(requested, actionDefinition.schema);
1533
+ // A later step in this same manifest may reference this one; its identity
1534
+ // and schema exist now even though the flow does not carry it yet.
1535
+ pendingSteps.push({ name: requested.type, order: String(requested.order), uiUniqueIdentifier, inputs: insertInputs });
1536
+ actionInserts.push({
1537
+ actionTypeSysId: resolved.id,
1538
+ flowSysId: flowId,
1539
+ generationSource: '',
1540
+ type: 'action',
1541
+ order: String(requested.order),
1542
+ parent: '',
1543
+ uiUniqueIdentifier,
1544
+ parentUiId: '',
1545
+ metadata: JSON.stringify(parseMaybeJson(actionDefinition.definition.metadata, {})),
1546
+ inputs: insertInputs,
1547
+ });
1548
+ changedActionInputs.set(uiUniqueIdentifier, new Set(Object.keys(requested.inputs || {})));
1549
+ for (const [input, after] of Object.entries(requested.inputs || {})) {
1550
+ changes.push({ component: 'action', order: requested.order, type: requested.type, input, before: null, after });
1551
+ collectPills(after, uiUniqueIdentifier, input);
1552
+ }
1553
+ } else {
1554
+ const existing = await resolveExistingAction(sdk, existingActions, requested, index);
1555
+ const update = buildActionUpdate(existing, requested, index);
1556
+ actionUpdates.push(update);
1557
+ const uiId = stringValue(existing.uiUniqueIdentifier || existing.ui_unique_identifier);
1558
+ if (actionTargets.has(uiId)) throw new Error(`Duplicate action update for order ${requested.order}; combine input changes in one action entry`);
1559
+ actionTargets.set(uiId, existing);
1560
+ changedActionInputs.set(uiId, new Set(Object.keys(requested.inputs)));
1561
+ for (const [input, after] of Object.entries(requested.inputs)) {
1562
+ changes.push({ component: 'action', order: requested.order, type: requested.type, input, before: inputRawValue(inputList(existing).find(field => field.name === input)), after });
1563
+ collectPills(after, uiId, input);
1564
+ }
1565
+ }
1243
1566
  }
1567
+
1244
1568
  const savedStages = stageList(beforeDefinition);
1245
1569
  const savedStageById = new Map(savedStages.map(stage => [stringValue(stage.stageId || stage.stage_id), stage]));
1570
+ // The provider replaces a flow's whole stage list when the patch inserts
1571
+ // stages, so an insert-only manifest silently drops the stages already there.
1572
+ // Refuse before any write rather than let the preservation check fail after.
1573
+ const namedStageIds = new Set(stageUpdates.map(update => update.stageId));
1574
+ const unlistedStages = savedStages.filter(stage => !namedStageIds.has(stringValue(stage.stageId || stage.stage_id)));
1575
+ if (stageInserts.length && unlistedStages.length) {
1576
+ const names = unlistedStages.map(stage => stringValue(stage.label)).filter(Boolean).join(', ');
1577
+ throw new Error(`Flow ${flowId} already has ${unlistedStages.length} stage(s) (${names}); inserting stages replaces the flow's stage list. Name every existing stage with its stageId in the manifest so it is kept. No content write attempted.`);
1578
+ }
1246
1579
  for (const update of stageUpdates) {
1247
1580
  const before = savedStageById.get(update.stageId);
1248
1581
  if (!before) throw new Error(`Flow ${flowId} has no stage ${update.stageId}; omit stageId to insert a new stage`);
@@ -1254,7 +1587,218 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1254
1587
  for (const insert of stageInserts) {
1255
1588
  changes.push({ component: 'stage', stage: insert.label, input: 'insert', before: null, after: { order: insert.order, componentIndexes: insert.componentIndexes } });
1256
1589
  }
1257
- if (triggerUpdates.length === 0 && actionUpdates.length === 0 && stageInserts.length === 0 && stageUpdates.length === 0) throw new Error(`Flow ${flowId} update has no supported changes`);
1590
+
1591
+ // Handle flowVariables insertion
1592
+ const requestedVariables = manifest.flowVariables || manifest.variables || [];
1593
+ const existingVars = beforeDefinition.flowVariables || [];
1594
+ for (const [varIdx, v] of requestedVariables.entries()) {
1595
+ const label = v.label || v.name;
1596
+ const name = (v.name || v.label).toLowerCase().replace(/[^a-z0-9_]/g, '');
1597
+ const rawType = (v.type || 'string').toLowerCase();
1598
+ const TYPE_MAP = {
1599
+ 'string': { type: 'string', label: 'String' },
1600
+ 'boolean': { type: 'boolean', label: 'True/False' },
1601
+ 'true/false': { type: 'boolean', label: 'True/False' },
1602
+ 'bool': { type: 'boolean', label: 'True/False' },
1603
+ 'integer': { type: 'integer', label: 'Integer' },
1604
+ 'int': { type: 'integer', label: 'Integer' },
1605
+ 'decimal': { type: 'decimal', label: 'Decimal' },
1606
+ 'float': { type: 'float', label: 'Floating Point Number' },
1607
+ 'date': { type: 'glide_date', label: 'Date' },
1608
+ 'glide_date': { type: 'glide_date', label: 'Date' },
1609
+ 'date/time': { type: 'glide_date_time', label: 'Date/Time' },
1610
+ 'datetime': { type: 'glide_date_time', label: 'Date/Time' },
1611
+ 'glide_date_time': { type: 'glide_date_time', label: 'Date/Time' },
1612
+ 'reference': { type: 'reference', label: 'Reference' },
1613
+ 'choice': { type: 'choice', label: 'Choice' },
1614
+ 'array.string': { type: 'array.string', label: 'Array.String' },
1615
+ 'array.reference': { type: 'array.reference', label: 'Array.Reference' },
1616
+ 'array.integer': { type: 'array.integer', label: 'Array.Integer' },
1617
+ 'array.boolean': { type: 'array.boolean', label: 'Array.True/False' },
1618
+ 'json': { type: 'json', label: 'JSON' },
1619
+ 'html': { type: 'html', label: 'HTML' }
1620
+ };
1621
+ const mapped = TYPE_MAP[rawType] || { type: rawType, label: v.type_label || (rawType.charAt(0).toUpperCase() + rawType.slice(1)) };
1622
+ const type = mapped.type;
1623
+ const type_label = v.type_label || mapped.label;
1624
+ const varOrder = v.order || (existingVars.length + varIdx + 1);
1625
+ const varUiId = v.uiUniqueIdentifier || idFactory();
1626
+ flowVariableInserts.push({
1627
+ label,
1628
+ name,
1629
+ type,
1630
+ type_label,
1631
+ order: varOrder,
1632
+ mandatory: Boolean(v.mandatory),
1633
+ readonly: Boolean(v.readonly),
1634
+ attributes: `sourceUiUniqueId=,sourceType=,sourceId=,uiUniqueId=${varUiId},`,
1635
+ uiDisplayType: type,
1636
+ uiDisplayTypeLabel: type_label
1637
+ });
1638
+ changes.push({ component: 'flowVariable', input: name, before: null, after: { label, type, order: varOrder } });
1639
+ }
1640
+
1641
+ // Handle flowLogics insertion and update
1642
+ const requestedLogics = manifest.flowLogics || manifest.logic || [];
1643
+ const logicTypeKey = t => String(t || '').toLowerCase().trim();
1644
+ const logicUiMap = new Map(); // order -> uiUniqueIdentifier
1645
+
1646
+ for (const [logicIdx, l] of requestedLogics.entries()) {
1647
+ const lType = logicTypeKey(l.type || l.name);
1648
+ const logicDef = FLOW_LOGIC_DEFINITIONS[lType] || {
1649
+ id: l.definitionId || l.id || '',
1650
+ name: l.name || l.type,
1651
+ type: (l.type || '').toUpperCase(),
1652
+ description: '',
1653
+ compilationClass: '',
1654
+ order: l.order || logicIdx + 1,
1655
+ connectedTo: l.connectedTo || '',
1656
+ attributes: 'allow_children=true,allow_siblings=true,'
1657
+ };
1658
+
1659
+ const uiUniqueIdentifier = l.uiUniqueIdentifier || idFactory();
1660
+ logicUiMap.set(String(l.order), uiUniqueIdentifier);
1661
+ const parentUiId = l.parentUiId || (l.parent ? (logicUiMap.get(String(l.parent)) || l.parent) : '');
1662
+ const connectedTo = l.connectedTo || (l.connectedToOrder ? (logicUiMap.get(String(l.connectedToOrder)) || l.connectedToOrder) : logicDef.connectedTo);
1663
+
1664
+ let resolvedCondition = String(l.condition || '').replace(/\{\{(?:step_)?(\d+)\.([^}]+)\}\}/g, (match, order, field) => {
1665
+ const ui = actionUiMap.get(String(order)) || logicUiMap.get(String(order));
1666
+ return ui ? '{{' + ui + '.' + field + '}}' : match;
1667
+ });
1668
+
1669
+ const inputs = [];
1670
+ collectPills(resolvedCondition, uiUniqueIdentifier, 'condition');
1671
+
1672
+ if (lType === 'if' || lType === 'else if') {
1673
+ inputs.push({
1674
+ name: 'condition_name',
1675
+ value: { schemaless: false, schemalessValue: '', value: l.condition_name || l.conditionName || l.label || '' }
1676
+ });
1677
+ inputs.push({
1678
+ name: 'condition',
1679
+ value: { schemaless: false, schemalessValue: '', value: resolvedCondition }
1680
+ });
1681
+ }
1682
+
1683
+ const flowVarsArray = [];
1684
+ if (lType === 'set flow variables' && l.values) {
1685
+ for (const [varName, varVal] of Object.entries(l.values)) {
1686
+ flowVarsArray.push({
1687
+ id: '',
1688
+ name: varName,
1689
+ children: [],
1690
+ displayValue: { value: '' },
1691
+ value: { schemaless: false, schemalessValue: '', value: String(varVal) }
1692
+ });
1693
+ }
1694
+ }
1695
+
1696
+ flowLogicInserts.push({
1697
+ order: String(l.order || logicIdx + 1),
1698
+ uiUniqueIdentifier,
1699
+ parent: parentUiId,
1700
+ parentUiId,
1701
+ connectedTo,
1702
+ metadata: '{"predicates":[]}',
1703
+ flowSysId: flowId,
1704
+ generationSource: '',
1705
+ definitionId: logicDef.id,
1706
+ type: 'flowlogic',
1707
+ inputs,
1708
+ outputsToAssign: [],
1709
+ ...(flowVarsArray.length ? { flowVariables: flowVarsArray } : {}),
1710
+ flowLogicDefinition: {
1711
+ id: logicDef.id,
1712
+ name: logicDef.name,
1713
+ description: logicDef.description,
1714
+ connectedTo: logicDef.connectedTo,
1715
+ quiescence: 'never',
1716
+ compilationClass: logicDef.compilationClass,
1717
+ order: logicDef.order,
1718
+ type: logicDef.type,
1719
+ visible: true,
1720
+ attributes: logicDef.attributes,
1721
+ userCanRead: true,
1722
+ category: '',
1723
+ inputs: [],
1724
+ variables: '[]'
1725
+ }
1726
+ });
1727
+
1728
+ changes.push({ component: 'flowLogic', order: l.order, type: logicDef.name, input: 'insert', before: null, after: { parent: parentUiId, connectedTo } });
1729
+ }
1730
+
1731
+ // Handle deletions by step order or uiUniqueIdentifier
1732
+ const rawDeletes = manifest.deleteSteps || manifest.delete || manifest.deleteOrders || [];
1733
+ const deleteTargets = new Set((Array.isArray(rawDeletes) ? rawDeletes : [rawDeletes]).map(String));
1734
+ if (deleteTargets.size > 0) {
1735
+ const existingLogics = beforeDefinition.flowLogicInstances || beforeDefinition.flowLogics || [];
1736
+ for (const a of existingActions) {
1737
+ const uiId = stringValue(a.uiUniqueIdentifier || a.ui_unique_identifier);
1738
+ const targetId = stringValue(a.sysId || a.id || a.sys_id || uiId);
1739
+ if (deleteTargets.has(String(a.order)) || deleteTargets.has(uiId) || deleteTargets.has(targetId)) {
1740
+ actionDeletes.push(targetId);
1741
+ changes.push({ component: 'action', order: a.order, type: a.name, input: 'delete', before: targetId, after: null });
1742
+ }
1743
+ }
1744
+ for (const fl of existingLogics) {
1745
+ const uiId = stringValue(fl.uiUniqueIdentifier || fl.ui_unique_identifier);
1746
+ const targetId = stringValue(fl.sysId || fl.id || fl.sys_id || uiId);
1747
+ if (deleteTargets.has(String(fl.order)) || deleteTargets.has(uiId) || deleteTargets.has(targetId)) {
1748
+ flowLogicDeletes.push(targetId);
1749
+ changes.push({ component: 'flowLogic', order: fl.order, type: fl.name, input: 'delete', before: targetId, after: null });
1750
+ }
1751
+ }
1752
+ }
1753
+ // Register every referenced pill so the canvas can draw it. Runs after every
1754
+ // collection point (actions and logic blocks) so no reference is missed.
1755
+ // Existing entries keep their label/type; a pill this flow has never seen gets
1756
+ // a label resolved from its producing step.
1757
+ const labelCacheInserts = [];
1758
+ const existingLabelCache = readLabelCache(beforeDefinition);
1759
+ const labelCacheEntry = ({ name, label, type, baseType, usedInstances }) => {
1760
+ // The provider stores usedInstances as a map, but a map key is a UUID and an
1761
+ // unquoted UUID key is not valid GraphQL. Send the array form it accepts.
1762
+ const instances = Object.entries(usedInstances || {}).flatMap(([uiUniqueIdentifier, inputNames]) =>
1763
+ (Array.isArray(inputNames) ? inputNames : [inputNames]).map(inputName => ({ uiUniqueIdentifier, inputName })));
1764
+ const entry = { name, usedInstances: instances };
1765
+ if (label) entry.label = label;
1766
+ if (type) entry.type = type;
1767
+ if (baseType) entry.base_type = baseType;
1768
+ return entry;
1769
+ };
1770
+ const mergeUsedInstances = (existing, instances) => {
1771
+ const merged = { ...(existing || {}) };
1772
+ for (const { uiUniqueIdentifier, inputName } of instances) {
1773
+ if (!merged[uiUniqueIdentifier]) merged[uiUniqueIdentifier] = [];
1774
+ if (!merged[uiUniqueIdentifier].includes(inputName)) merged[uiUniqueIdentifier].push(inputName);
1775
+ }
1776
+ return merged;
1777
+ };
1778
+ for (const [pillName, instances] of pillToInstances.entries()) {
1779
+ const existing = existingLabelCache.find(entry => entry.name === pillName);
1780
+ const usedInstances = mergeUsedInstances(existing?.usedInstances, instances);
1781
+ // An entry with no caption draws nothing, so a missing label is repaired
1782
+ // rather than passed through; a missing type is filled in when resolvable.
1783
+ let binding = null;
1784
+ if (!existing?.label) {
1785
+ binding = resolvePillBinding(beforeDefinition, pillName, flowId, existingLabelCache, pendingSteps);
1786
+ } else if (!existing.type) {
1787
+ try { binding = resolvePillBinding(beforeDefinition, pillName, flowId, existingLabelCache, pendingSteps); } catch { binding = null; }
1788
+ }
1789
+ if (existing) {
1790
+ labelCacheUpdates.push(labelCacheEntry({
1791
+ ...existing,
1792
+ label: existing.label || binding.label,
1793
+ type: existing.type || binding.type,
1794
+ baseType: existing.baseType || binding.type,
1795
+ usedInstances,
1796
+ }));
1797
+ } else {
1798
+ labelCacheInserts.push(labelCacheEntry({ name: pillName, label: binding.label, type: binding.type, baseType: binding.type, usedInstances }));
1799
+ }
1800
+ }
1801
+ if (triggerUpdates.length === 0 && actionUpdates.length === 0 && actionInserts.length === 0 && actionDeletes.length === 0 && flowVariableInserts.length === 0 && flowLogicInserts.length === 0 && flowLogicDeletes.length === 0 && stageInserts.length === 0 && stageUpdates.length === 0) throw new Error(`Flow ${flowId} update has no supported changes`);
1258
1802
  if (options.preview) return {
1259
1803
  preview: true,
1260
1804
  flow: { id: flowId, name: target.flowName, status: lifecycle.status, active: lifecycle.active },
@@ -1281,9 +1825,48 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1281
1825
  const outcome = await withFlowSafeEdit(sdk, instance, flowId, beforeDefinition.updated, async () => {
1282
1826
  let completedStage = 'validated';
1283
1827
  try {
1828
+ if (stageInserts.length > 0) {
1829
+ const stagesPayload = {};
1830
+ for (const s of stageInserts) {
1831
+ stagesPayload[s.stageId] = {
1832
+ stageId: s.stageId,
1833
+ duration: s.duration || STAGE_DURATION,
1834
+ componentIndexes: s.componentIndexes || [],
1835
+ label: s.label,
1836
+ value: s.value,
1837
+ type: s.type || 'standard',
1838
+ order: s.order,
1839
+ alwaysShow: s.alwaysShow ?? true,
1840
+ states: {
1841
+ pending: 'Pending - has not started',
1842
+ in_progress: 'In progress',
1843
+ skipped: 'Skipped',
1844
+ complete: 'Completed',
1845
+ error: 'Error'
1846
+ },
1847
+ system: Boolean(s._system ?? s.system)
1848
+ };
1849
+ }
1850
+ const stageRegRes = await sdk.request(`${instance}${FLOW_ENDPOINT}/${encodeURIComponent(flowId)}/stages?sysparm_transaction_scope=${encodeURIComponent(scope)}`, {
1851
+ method: 'PUT',
1852
+ body: JSON.stringify(stagesPayload)
1853
+ });
1854
+ const returnedStages = stageRegRes?.result?.data || {};
1855
+ // The PUT writes stage rows before the patch runs, so a silent omission
1856
+ // here would leave the flow holding stages nothing points at.
1857
+ const unconfirmed = [];
1858
+ for (const s of stageInserts) {
1859
+ if (returnedStages[s.stageId]?.id) s.id = returnedStages[s.stageId].id;
1860
+ else unconfirmed.push(s.label || s.stageId);
1861
+ }
1862
+ if (unconfirmed.length) {
1863
+ throw new Error(`Flow ${flowId} stage registration did not confirm ${unconfirmed.join(', ')}; those stages may already be attached to the flow. Inspect it before retrying`);
1864
+ }
1865
+ }
1866
+ const patchQuery = buildFlowUpdateMutation({ flowId, triggerUpdates, actionUpdates, actionInserts, actionDeletes, flowVariableInserts, flowLogicInserts, flowLogicUpdates, flowLogicDeletes, labelCacheUpdates, labelCacheInserts, stageInserts, stageUpdates });
1284
1867
  const patchResponse = await mutationContext('trigger_and_actions_update', readUpdateSet, snapshots, () => sdk.request(`${instance}${GRAPHQL_ENDPOINT}`, {
1285
1868
  method: 'POST',
1286
- body: JSON.stringify({ query: buildFlowUpdateMutation({ flowId, triggerUpdates, actionUpdates, stageInserts, stageUpdates }), variables: {} }),
1869
+ body: JSON.stringify({ query: patchQuery, variables: {} }),
1287
1870
  }), updateSet => readUpdateSetCapture(sdk, updateSet, flowId));
1288
1871
  assertGraphQLSuccess(patchResponse, 'Flow trigger/action update');
1289
1872
  completedStage = 'patch_acknowledged';
@@ -1291,7 +1874,10 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1291
1874
  // Only requested values may differ. Preserve array order and opaque fields.
1292
1875
  // `stages` is compared separately below: a stage edit may touch specific
1293
1876
  // fields, while every stage the manifest did not name must stay identical.
1294
- for (const field of ['flowVariables', 'flowLogicInstances', 'subFlowInstances', 'flowInputs', 'flowOutputs', 'inputs', 'outputs']) {
1877
+ const checkFields = ['subFlowInstances', 'flowInputs', 'flowOutputs', 'inputs', 'outputs'];
1878
+ if (flowVariableInserts.length === 0) checkFields.push('flowVariables');
1879
+ if (flowLogicInserts.length === 0 && flowLogicUpdates.length === 0 && flowLogicDeletes.length === 0) checkFields.push('flowLogicInstances');
1880
+ for (const field of checkFields) {
1295
1881
  if (!isDeepStrictEqual(beforeDefinition[field], processflow[field])) throw new Error(`Flow ${flowId} changed omitted ${field}; preservation failed`);
1296
1882
  }
1297
1883
  if (stageInserts.length || stageUpdates.length) {
@@ -1309,13 +1895,31 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1309
1895
  throw new Error(`Flow ${flowId} changed omitted stages; preservation failed`);
1310
1896
  }
1311
1897
  if (!triggerUpdate && !isDeepStrictEqual(beforeDefinition.triggerInstances, processflow.triggerInstances)) throw new Error(`Flow ${flowId} changed omitted triggerInstances`);
1312
- const maskActions = definition => findExistingActions(definition).map(action => {
1313
- const copy = clone(action);
1314
- const changed = changedActionInputs.get(stringValue(action.uiUniqueIdentifier || action.ui_unique_identifier));
1315
- for (const [index, input] of inputList(copy).entries()) if (changed?.has(input.name)) inputList(copy)[index] = maskInputValue(input);
1316
- return copy;
1317
- });
1318
- if (!isDeepStrictEqual(maskActions(beforeDefinition), maskActions(processflow))) throw new Error(`Flow ${flowId} changed omitted action fields; preservation failed`);
1898
+ const insertedUiIds = new Set(actionInserts.map(a => a.uiUniqueIdentifier));
1899
+ const deletedActionIds = new Set(actionDeletes);
1900
+ const maskActions = (definition, isAfter = false) => findExistingActions(definition)
1901
+ .filter(action => {
1902
+ const uiId = stringValue(action.uiUniqueIdentifier || action.ui_unique_identifier);
1903
+ const sId = stringValue(action.sysId || action.id || action.sys_id);
1904
+ if (isAfter && insertedUiIds.has(uiId)) return false;
1905
+ if (!isAfter && (deletedActionIds.has(uiId) || deletedActionIds.has(sId))) return false;
1906
+ return true;
1907
+ })
1908
+ .map(action => {
1909
+ const copy = clone(action);
1910
+ const changed = changedActionInputs.get(stringValue(action.uiUniqueIdentifier || action.ui_unique_identifier));
1911
+ for (const [index, input] of inputList(copy).entries()) if (changed?.has(input.name)) inputList(copy)[index] = maskInputValue(input);
1912
+ return copy;
1913
+ });
1914
+ if (!isDeepStrictEqual(maskActions(beforeDefinition), maskActions(processflow, true))) throw new Error(`Flow ${flowId} changed omitted action fields; preservation failed`);
1915
+ // A pill the provider accepted but did not store still renders blank, so
1916
+ // read the cache back instead of trusting the mutation acknowledgement.
1917
+ const readbackCache = readLabelCache(processflow);
1918
+ for (const entry of [...labelCacheInserts, ...labelCacheUpdates]) {
1919
+ const saved = readbackCache.find(candidate => candidate.name === entry.name);
1920
+ if (!saved) throw new Error(`Flow ${flowId} did not persist data pill ${entry.name} to label_cache; the reference would render blank`);
1921
+ if (!saved.label) throw new Error(`Flow ${flowId} persisted data pill ${entry.name} without a label; the reference would render blank`);
1922
+ }
1319
1923
  const readbackTrigger = findArray(processflow, 'triggerInstances')[0];
1320
1924
  if (triggerUpdate) {
1321
1925
  if (!readbackTrigger || findId(readbackTrigger, ['sysId', 'sys_id', 'id', 'triggerId']) !== triggerUpdate.id) throw new Error(`Flow ${flowId} trigger update was not readable after mutation`);