@jacebenson/jsn 5.5.1-dev.164.1 → 5.5.1-dev.166.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 +750 -174
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jacebenson/jsn",
3
- "version": "5.5.1-dev.164.1",
3
+ "version": "5.5.1-dev.166.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": {
@@ -28,7 +28,7 @@ const FLOW_RECORD_FIELDS = 'sys_id,name,sys_scope,scope,active,status,type,sys_u
28
28
 
29
29
  // Everything this partial-update contract still cannot do, whatever the
30
30
  // lifecycle state. Published edits reuse the same component rules.
31
- const DEFERRED_LIFECYCLE = ['publish/activation', 'Flow Logic', 'subflows', 'flow variables', 'error handling'];
31
+ const DEFERRED_LIFECYCLE = ['publish/activation', 'subflows', 'flow variables'];
32
32
 
33
33
  function supportedLifecycle(published) {
34
34
  return published
@@ -155,10 +155,10 @@ export function validateFlowManifest(manifest) {
155
155
  if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) throw new Error('Flow manifest must be a JSON object');
156
156
  if (!String(manifest.name || '').trim()) throw new Error('Flow manifest requires name');
157
157
  if (!String(manifest.scope || '').trim()) throw new Error('Flow manifest requires scope');
158
- if (manifest.logic !== undefined) throw new Error('Flow Logic is unsupported in this creation slice');
158
+ validateLogicManifest(manifest);
159
159
  if (manifest.subflows !== undefined || manifest.subFlows !== undefined) throw new Error('Subflows are unsupported in this creation slice');
160
160
  if (manifest.variables !== undefined || manifest.flowVariables !== undefined) throw new Error('Flow-variable lifecycle is unsupported in this creation slice');
161
- if (manifest.errorHandling !== undefined) throw new Error('Error handling is unsupported in this creation slice');
161
+ if (manifest.errorHandling !== undefined) validateErrorHandling(manifest.errorHandling);
162
162
  if (manifest.stages !== undefined) validateStages(manifest.stages);
163
163
  if (manifest.stageTemplate !== undefined && !String(manifest.stageTemplate).trim()) throw new Error('Flow manifest stageTemplate must not be empty');
164
164
  if (manifest.stageSet !== undefined && !String(manifest.stageSet).trim()) throw new Error('Flow manifest stageSet must not be empty');
@@ -175,6 +175,8 @@ export function validateFlowManifest(manifest) {
175
175
  if (!Array.isArray(manifest.actions)) throw new Error('Flow manifest requires an actions array');
176
176
  for (const [index, action] of manifest.actions.entries()) {
177
177
  if (!action || typeof action !== 'object' || !String(action.type || '').trim()) throw new Error(`Action ${index + 1} requires type`);
178
+ for (const key of Object.keys(action)) if (!['type', 'inputs', 'order', 'parent', 'parentOrder', 'parentUiId'].includes(key)) throw new Error(`Unsupported action field ${key}`);
179
+ if (action.order !== undefined && (!Number.isInteger(action.order) || action.order < 1)) throw new Error('Action order must be a positive integer');
178
180
  if (action.inputs !== undefined && (!action.inputs || typeof action.inputs !== 'object' || Array.isArray(action.inputs))) throw new Error(`Action ${index + 1} inputs must be an object`);
179
181
  }
180
182
  return manifest;
@@ -320,6 +322,20 @@ export async function resolveStageTemplate(sdk, templateIdentifier) {
320
322
  return finalStages;
321
323
  }
322
324
 
325
+ export function validateErrorHandling(eh) {
326
+ if (eh === null || typeof eh !== 'object' || Array.isArray(eh)) throw new Error('Flow errorHandling must be an object');
327
+ for (const key of Object.keys(eh)) if (key !== 'actions') throw new Error(`Unsupported errorHandling field ${key}`);
328
+ if (eh.actions !== undefined) {
329
+ if (!Array.isArray(eh.actions)) throw new Error('Flow errorHandling.actions must be an array');
330
+ for (const [index, action] of eh.actions.entries()) {
331
+ if (!action || typeof action !== 'object' || Array.isArray(action)) throw new Error(`Error action ${index + 1} must be an object`);
332
+ if (typeof action.type !== 'string' || !action.type.trim()) throw new Error(`Error action ${index + 1} requires type`);
333
+ for (const key of Object.keys(action)) if (!['type', 'inputs'].includes(key)) throw new Error(`Unsupported error action field ${key}; identities are allocated by the provider editor`);
334
+ if (action.inputs !== undefined && (!action.inputs || typeof action.inputs !== 'object' || Array.isArray(action.inputs))) throw new Error(`Error action ${index + 1} inputs must be an object`);
335
+ }
336
+ }
337
+ }
338
+
323
339
  export function validateStages(stages, { update = false } = {}) {
324
340
  if (!Array.isArray(stages)) throw new Error('Flow stages must be an array');
325
341
  for (const [index, stage] of stages.entries()) {
@@ -428,7 +444,7 @@ export async function readCatalogItemVariables(sdk, instance, flowId, catalogIte
428
444
  };
429
445
  }
430
446
 
431
- export function buildFlowPatchMutation({ flowId, trigger, actions }) {
447
+ export function buildFlowPatchMutation({ flowId, trigger, actions, flowLogicInserts = [], labelCacheInserts = [] }) {
432
448
  const triggerInsert = {
433
449
  flowSysId: trigger.flowSysId,
434
450
  name: trigger.name,
@@ -450,14 +466,55 @@ export function buildFlowPatchMutation({ flowId, trigger, actions }) {
450
466
  metadata: action.metadata,
451
467
  inputs: action.inputs,
452
468
  }));
453
- const patch = `flowPatch: {flowId: ${gqlString(flowId)}, triggerInstances: {insert: [${gqlInputObject(triggerInsert)}]}, actions: {insert: [${actionInsert.map(gqlInputObject).join(', ')}]}}`;
469
+ const extra = `${flowLogicInserts.length ? `, flowLogics: {insert: [${flowLogicInserts.map(gqlInputObject).join(', ')}]}` : ''}${labelCacheInserts.length ? `, labelCache: {insert: [${labelCacheInserts.map(gqlInputObject).join(', ')}]}` : ''}`;
470
+ const patch = `flowPatch: {flowId: ${gqlString(flowId)}, triggerInstances: {insert: [${gqlInputObject(triggerInsert)}]}, actions: {insert: [${actionInsert.map(gqlInputObject).join(', ')}]}${extra}}`;
454
471
  // `triggerInstances.updates` is a leaf [String] on this schema; only `inserts`
455
472
  // carries identities, and only for triggers does `inserts` lack a uiUniqueIdentifier.
456
- return `mutation { global { snFlowDesigner { flow(${patch}) { triggerInstances { inserts { sysId } updates } actions { inserts { sysId uiUniqueIdentifier } } } } } }`;
473
+ return `mutation { global { snFlowDesigner { flow(${patch}) { triggerInstances { inserts { sysId } updates } actions { inserts { sysId uiUniqueIdentifier } } ${flowLogicInserts.length ? 'flowLogics { inserts { sysId uiUniqueIdentifier } }' : ''} } } } }`;
457
474
  }
458
475
 
459
476
 
460
477
  const FLOW_LOGIC_DEFINITIONS = {
478
+ 'top level try': {
479
+ id: 'e9060aa2c3013010ace8b740ad40dd51',
480
+ name: 'Top Level Try',
481
+ type: 'TOP_LEVEL_TRY',
482
+ description: 'Begin a top level try block',
483
+ compilationClass: 'com.glide.flow.compiler.logic_block.TryCompiler',
484
+ order: 18,
485
+ connectedTo: '',
486
+ attributes: 'allow_siblings=true,draw_curve=true,line_type=q_curve,visible_in_picker=false,visible_in_ui=false,',
487
+ },
488
+ 'top level catch': {
489
+ id: '35d60003e6022010a5e40cdd1254dd23',
490
+ name: 'Top Level Catch',
491
+ type: 'TOP_LEVEL_CATCH',
492
+ description: 'Catch and handle an error',
493
+ compilationClass: 'com.glide.flow.compiler.logic_block.CatchCompiler',
494
+ order: 17,
495
+ connectedTo: '07223332de022010ec58424b73829721,e9060aa2c3013010ace8b740ad40dd51',
496
+ attributes: 'allow_siblings=true,draw_curve=true,line_type=q_curve,visible_in_picker=false,visible_in_ui=false,',
497
+ },
498
+ 'try': {
499
+ id: '07223332de022010ec58424b73829721',
500
+ name: 'Try',
501
+ type: 'TRY',
502
+ description: 'Allow a flow to continue running when an error occurs within a flow logic block. Run a sequence of actions in response to errors within the flow logic block',
503
+ compilationClass: 'com.glide.flow.compiler.logic_block.TryCompiler',
504
+ order: 15,
505
+ connectedTo: '',
506
+ attributes: 'allow_siblings=true,disable_opening=true,draw_curve=true,icon_class=try,line_type=cc_curve,visible_in_picker=true,',
507
+ },
508
+ 'catch': {
509
+ id: '35d60003e6022010a5e40cdd1254dd21',
510
+ name: 'Catch',
511
+ type: 'CATCH',
512
+ description: 'Catch and handle an error',
513
+ compilationClass: 'com.glide.flow.compiler.logic_block.CatchCompiler',
514
+ order: 16,
515
+ connectedTo: '07223332de022010ec58424b73829721',
516
+ attributes: 'allow_siblings=true,disable_opening=true,draw_curve=true,icon_class=catch,line_type=q_curve,visible_in_picker=false,',
517
+ },
461
518
  'if': {
462
519
  id: 'af4e1945c3e232002841b63b12d3ae3e',
463
520
  name: 'If',
@@ -765,7 +822,7 @@ function verifyCreatedFlowReadback({ flowId, processflow, trigger, insertedTrigg
765
822
  if (savedInputs.length !== expected.inputs.length) throw new Error(`Created Action ${expected.uiUniqueIdentifier} input count did not match the installed schema`);
766
823
  for (const expectedInput of expected.inputs) {
767
824
  const actualInput = savedInputs.find(input => input.name === expectedInput.name);
768
- if (!actualInput || inputRawValue(actualInput) !== inputRawValue(expectedInput)) throw new Error(`Created Action ${expected.uiUniqueIdentifier} input ${expectedInput.name} did not match the requested value`);
825
+ if (!actualInput || !isDeepStrictEqual(inputRawValue(actualInput), inputRawValue(expectedInput))) throw new Error(`Created Action ${expected.uiUniqueIdentifier} input ${expectedInput.name} did not match the requested value`);
769
826
  }
770
827
  }
771
828
  }
@@ -888,10 +945,37 @@ async function resolveExistingAction(sdk, actions, requested, index) {
888
945
  return matches[0];
889
946
  }
890
947
 
948
+ function validateLogicManifest(manifest) {
949
+ if (manifest.logic !== undefined && manifest.flowLogics !== undefined) throw new Error('Specify logic or flowLogics, not both');
950
+ const logics = manifest.logic ?? manifest.flowLogics;
951
+ if (logics === undefined) return;
952
+ if (!Array.isArray(logics)) throw new Error('Flow logic must be an array');
953
+ const orders = new Set();
954
+ for (const l of logics) {
955
+ if (!l || typeof l !== 'object' || Array.isArray(l)) throw new Error('Flow logic must be an object');
956
+ for (const key of Object.keys(l)) if (!['order', 'type', 'name', 'parent', 'parentOrder', 'parentUiId', 'connectedTo', 'connectedToOrder', 'condition', 'condition_name', 'conditionName', 'label', 'values'].includes(key)) throw new Error(`Unsupported logic field ${key}; caller identities are not accepted`);
957
+ if (!Number.isInteger(l.order) || l.order < 1 || orders.has(l.order)) throw new Error('Logic order must be a unique positive integer');
958
+ orders.add(l.order);
959
+ if (l.type !== undefined && l.name !== undefined && String(l.type).toLowerCase().trim() !== String(l.name).toLowerCase().trim()) throw new Error('Conflicting logic type/name aliases');
960
+ if (!FLOW_LOGIC_DEFINITIONS[String(l.type || l.name || '').toLowerCase().trim()]) throw new Error('Unsupported flow logic type');
961
+ const logicType = String(l.type || l.name).toLowerCase().trim();
962
+ const labels = ['condition_name', 'conditionName', 'label'].filter(k => l[k] !== undefined);
963
+ if (labels.some(k => typeof l[k] !== 'string') || new Set(labels.map(k => l[k])).size > 1) throw new Error('Conflicting or malformed condition label aliases');
964
+ if (![ 'if', 'else if' ].includes(logicType) && (l.condition !== undefined || labels.length)) throw new Error('Condition fields are supported only on If and Else If');
965
+ if (l.values !== undefined && logicType !== 'set flow variables') throw new Error('Assignment values are supported only on Set Flow Variables');
966
+ if (l.values && Object.values(l.values).some(v => typeof v !== 'string')) throw new Error('Assignment values must be strings (literal or supported pill reference)');
967
+ if ((manifest.errorHandling !== undefined || manifest.errorHandler !== undefined) && ['top level try', 'top level catch'].includes(logicType)) throw new Error('Explicit top-level error blocks conflict with errorHandling');
968
+ if (l.condition !== undefined && typeof l.condition !== 'string') throw new Error('Logic condition must be a string');
969
+ if (l.values !== undefined && (!l.values || typeof l.values !== 'object' || Array.isArray(l.values))) throw new Error('Logic values must be an object');
970
+ for (const key of ['parent', 'parentOrder', 'parentUiId', 'connectedTo', 'connectedToOrder']) if (l[key] !== undefined && !((typeof l[key] === 'string' && l[key].trim()) || (Number.isInteger(l[key]) && l[key] > 0))) throw new Error(`Malformed logic ${key}`);
971
+ }
972
+ }
973
+
891
974
  export function validateFlowUpdateManifest(manifest) {
892
975
  if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) throw new Error('Flow update manifest must be a JSON object');
893
- const allowed = new Set(['scope', 'trigger', 'actions', 'stages', 'stageTemplate', 'stageSet', 'flowVariables', 'variables', 'flowLogics', 'logic', 'deleteSteps', 'delete', 'deleteOrders']);
976
+ const allowed = new Set(['scope', 'trigger', 'actions', 'stages', 'stageTemplate', 'stageSet', 'flowVariables', 'variables', 'flowLogics', 'logic', 'deleteSteps', 'delete', 'deleteOrders', 'errorHandling', 'errorHandler']);
894
977
  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`);
978
+ validateLogicManifest(manifest);
895
979
  if (manifest.scope !== undefined && !String(manifest.scope).trim()) throw new Error('Flow update scope must not be empty');
896
980
  if (manifest.trigger !== undefined) {
897
981
  if (!manifest.trigger || typeof manifest.trigger !== 'object' || Array.isArray(manifest.trigger)) throw new Error('Flow update trigger must be an object');
@@ -906,14 +990,21 @@ export function validateFlowUpdateManifest(manifest) {
906
990
  if (!Array.isArray(manifest.actions)) throw new Error('Flow update actions must be an array');
907
991
  for (const [index, action] of manifest.actions.entries()) {
908
992
  if (!action || typeof action !== 'object' || Array.isArray(action)) throw new Error(`Update action ${index + 1} must be an object`);
909
- for (const key of Object.keys(action)) if (!['order', 'type', 'inputs'].includes(key)) throw new Error(`Update action ${index + 1} field "${key}" is unsupported; caller-supplied identities are not accepted`);
993
+ for (const key of Object.keys(action)) if (!['order', 'type', 'inputs', 'parent', 'parentOrder', 'parentUiId'].includes(key)) throw new Error(`Update action ${index + 1} field "${key}" is unsupported; caller-supplied identities are not accepted`);
994
+ for (const key of ['parent', 'parentOrder', 'parentUiId']) if (action[key] !== undefined && !((typeof action[key] === 'string' && action[key].trim()) || (Number.isInteger(action[key]) && action[key] > 0))) throw new Error(`Malformed action ${key}`);
910
995
  if (!Number.isInteger(action.order) || action.order < 1 || !String(action.type || '').trim()) throw new Error(`Update action ${index + 1} requires a positive integer order and type`);
911
996
  if (!action.inputs || typeof action.inputs !== 'object' || Array.isArray(action.inputs)) throw new Error(`Update action ${index + 1} inputs must be an object`);
912
997
  if (Object.keys(action.inputs).length === 0) throw new Error(`Update action ${index + 1} inputs must contain at least one changed value`);
913
998
  }
914
999
  }
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');
1000
+ 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 && manifest.errorHandling === undefined && manifest.errorHandler === undefined) throw new Error('Flow update manifest must specify trigger, actions and/or stages');
916
1001
  if (manifest.stages !== undefined) validateStages(manifest.stages, { update: true });
1002
+ if (manifest.errorHandling !== undefined && manifest.errorHandler !== undefined) throw new Error('Specify errorHandling or errorHandler, not both');
1003
+ // Accepting the key without checking its shape would still insert the Try and
1004
+ // Catch blocks while silently dropping a malformed action list.
1005
+ for (const key of ['errorHandling', 'errorHandler']) {
1006
+ if (manifest[key] !== undefined) validateErrorHandling(manifest[key]);
1007
+ }
917
1008
  for (const key of ['stageTemplate', 'stageSet']) {
918
1009
  if (manifest[key] === undefined) continue;
919
1010
  if (typeof manifest[key] !== 'string' || !manifest[key].trim()) throw new Error(`Flow update ${key} must be a non-empty string`);
@@ -1232,6 +1323,580 @@ async function findCaptureElsewhere(sdk, flowId, intendedSetId) {
1232
1323
  return { checked: true, available: true, query: `nameLIKE${id}`, update_sets: [...bySet.values()] };
1233
1324
  }
1234
1325
 
1326
+ // Verify requested step content independently of the mutation acknowledgement.
1327
+ function labelCacheEntry({ name, label, type, baseType, usedInstances }) {
1328
+ // The provider stores usedInstances as a map, but a map key is a UUID and an
1329
+ // unquoted UUID key is not valid GraphQL. Send the array form it accepts.
1330
+ const instances = Object.entries(usedInstances || {}).flatMap(([uiUniqueIdentifier, inputNames]) =>
1331
+ (Array.isArray(inputNames) ? inputNames : [inputNames]).map(inputName => ({ uiUniqueIdentifier, inputName })));
1332
+ const entry = { name, usedInstances: instances };
1333
+ if (label) entry.label = label;
1334
+ if (type) entry.type = type;
1335
+ if (baseType) entry.base_type = baseType;
1336
+ return entry;
1337
+ }
1338
+
1339
+ function assertInsertedIdentities(response, definition, expected, kind, flowId) {
1340
+ if (!expected.length) return;
1341
+ const field = kind === 'action' ? 'actions' : 'flowLogics';
1342
+ let inserted = [];
1343
+ walk(response, object => { if (object[field]?.inserts) inserted = object[field].inserts; });
1344
+ const saved = kind === 'action' ? findExistingActions(definition) : (definition.flowLogicInstances || definition.flowLogics || []);
1345
+ for (const step of expected) {
1346
+ const matches = inserted.filter(s => s.uiUniqueIdentifier === step.uiUniqueIdentifier);
1347
+ const actual = saved.filter(s => stringValue(s.uiUniqueIdentifier || s.ui_unique_identifier) === step.uiUniqueIdentifier);
1348
+ const id = matches.length === 1 && findId(matches[0], ['sysId', 'sys_id', 'id']);
1349
+ if (!id || actual.length !== 1 || findId(actual[0], ['sysId', 'sys_id', 'id']) !== id) throw new Error(`Flow ${flowId} ${kind} ${step.uiUniqueIdentifier} persisted identity did not match the insert acknowledgement`);
1350
+ }
1351
+ }
1352
+
1353
+ // Compare the requested contract, allowing only additional provider fields.
1354
+ function requestedContentMatches(actual, expected) {
1355
+ if (Array.isArray(expected)) return Array.isArray(actual) && actual.length === expected.length && expected.every((v, i) => requestedContentMatches(actual[i], v));
1356
+ if (expected && typeof expected === 'object') return actual !== null && typeof actual === 'object' && Object.entries(expected).every(([k, v]) => requestedContentMatches(actual[k], v));
1357
+ return isDeepStrictEqual(actual, expected);
1358
+ }
1359
+
1360
+ function validateFinalStepPlan(before, actionInserts, actionUpdates, actionDeletes, logicInserts, logicUpdates, logicDeletes) {
1361
+ const surviving = (steps, updates, deletes) => steps.filter(s => !deletes.includes(stringValue(s.sysId || s.id || s.sys_id || s.uiUniqueIdentifier))).map(s => ({ ...s, ...updates.find(u => u.uiUniqueIdentifier === stringValue(s.uiUniqueIdentifier || s.ui_unique_identifier)) }));
1362
+ const steps = [...surviving(findExistingActions(before), actionUpdates, actionDeletes), ...surviving(before.flowLogicInstances || before.flowLogics || [], logicUpdates, logicDeletes), ...actionInserts, ...logicInserts];
1363
+ const orders = new Set(), identities = new Set();
1364
+ for (const s of steps) {
1365
+ const ui = stringValue(s.uiUniqueIdentifier || s.ui_unique_identifier), order = String(s.order);
1366
+ if ((s.order !== undefined && orders.has(order)) || (ui && identities.has(ui))) throw new Error('Ambiguous final step orders or identities');
1367
+ if (s.order !== undefined) orders.add(order);
1368
+ if (ui) identities.add(ui);
1369
+ }
1370
+ const byUi = new Map(steps.map(s => [stringValue(s.uiUniqueIdentifier || s.ui_unique_identifier), s]));
1371
+ const paired = new Set();
1372
+ const parentOf = s => stringValue(s.parentUiId || s.parent);
1373
+ for (const step of steps) {
1374
+ if (step.parent && step.parentUiId && step.parent !== step.parentUiId) throw new Error('Conflicting final parent aliases');
1375
+ const seen = new Set([stringValue(step.uiUniqueIdentifier || step.ui_unique_identifier)]);
1376
+ let parent = parentOf(step);
1377
+ while (parent && byUi.has(parent)) {
1378
+ if (seen.has(parent)) throw new Error('Cyclic final parent links');
1379
+ seen.add(parent); parent = parentOf(byUi.get(parent));
1380
+ }
1381
+ const catchType = { '35d60003e6022010a5e40cdd1254dd21': '07223332de022010ec58424b73829721', '35d60003e6022010a5e40cdd1254dd23': 'e9060aa2c3013010ace8b740ad40dd51' }[step.definitionId];
1382
+ if (!catchType) continue;
1383
+ const target = byUi.get(stringValue(step.connectedTo));
1384
+ if (!target || target.definitionId !== catchType) throw new Error('Catch must connect to a compatible Try');
1385
+ if (paired.has(step.connectedTo)) throw new Error('Ambiguous Catch pair: Try already paired');
1386
+ paired.add(step.connectedTo);
1387
+ if (parentOf(target) !== parentOf(step)) throw new Error('Catch and Try must be siblings with compatible parents');
1388
+ }
1389
+ }
1390
+
1391
+ function assertStepReadback(definition, expectedSteps, kind, flowId) {
1392
+ const saved = kind === 'action' ? findExistingActions(definition) : (definition.flowLogicInstances || definition.flowLogics || []);
1393
+ for (const expected of expectedSteps) {
1394
+ const matches = saved.filter(step => stringValue(step.uiUniqueIdentifier || step.ui_unique_identifier) === expected.uiUniqueIdentifier);
1395
+ if (matches.length !== 1) throw new Error(`Flow ${flowId} ${kind} ${expected.uiUniqueIdentifier} was not uniquely persisted`);
1396
+ const actual = matches[0];
1397
+ if (!findId(actual, ['sysId', 'id', 'sys_id'])) throw new Error(`Flow ${flowId} ${kind} has no persisted identity`);
1398
+ for (const key of ['order', 'parent', 'parentUiId', 'connectedTo', 'definitionId', 'actionTypeSysId']) {
1399
+ if (expected[key] === undefined) continue;
1400
+ const value = key === 'actionTypeSysId' ? actionTypeIdOf(actual) : actual[key];
1401
+ if (String(value ?? '') !== String(expected[key])) throw new Error(`Flow ${flowId} ${kind} ${expected.uiUniqueIdentifier} ${key} did not match requested value`);
1402
+ }
1403
+ if (expected.flowVariables && !requestedContentMatches(actual.flowVariables, expected.flowVariables)) throw new Error(`Flow ${flowId} ${kind} assignments did not match requested content`);
1404
+ if (expected.inputs) {
1405
+ for (const input of expected.inputs) {
1406
+ const found = inputList(actual).filter(i => i.name === input.name);
1407
+ if (found.length !== 1 || !requestedContentMatches(found[0], input)) throw new Error(`Flow ${flowId} ${kind} ${expected.uiUniqueIdentifier} input ${input.name} did not match the requested value; preservation failed`);
1408
+ }
1409
+ }
1410
+ }
1411
+ }
1412
+
1413
+ function assertLogicPreserved(before, after, inserts, updates, deletes, flowId) {
1414
+ const ids = new Set(inserts.map(l => l.uiUniqueIdentifier));
1415
+ const mask = (definition, isAfter) => (definition.flowLogicInstances || definition.flowLogics || []).filter(l => {
1416
+ const ui = stringValue(l.uiUniqueIdentifier || l.ui_unique_identifier);
1417
+ return !(isAfter ? ids.has(ui) : deletes.includes(stringValue(l.sysId || l.id || l.sys_id || ui)));
1418
+ }).map(l => {
1419
+ const copy = clone(l);
1420
+ const update = updates.find(u => u.uiUniqueIdentifier === stringValue(l.uiUniqueIdentifier || l.ui_unique_identifier));
1421
+ if (update) for (const key of Object.keys(update)) if (!['uiUniqueIdentifier', 'type'].includes(key)) delete copy[key];
1422
+ return copy;
1423
+ });
1424
+ if (!isDeepStrictEqual(mask(before, false), mask(after, true))) throw new Error(`Flow ${flowId} changed omitted logic fields; preservation failed`);
1425
+ }
1426
+
1427
+ async function planErrorHandling({ sdk, instance, scope, flowId, beforeDefinition, existingActions, actionInserts, actionUpdates, flowLogicInserts, flowLogicUpdates, changes, idFactory, actionUiMap, pendingSteps, changedActionInputs, collectPills, errorHandlingInput, actionTargets = new Map() }) {
1428
+ const existingLogics = beforeDefinition.flowLogicInstances || beforeDefinition.flowLogics || [];
1429
+ const existingSteps = [...existingActions, ...existingLogics];
1430
+ if (existingSteps.some(s => !stringValue(s.uiUniqueIdentifier || s.ui_unique_identifier) || !Number.isInteger(Number(s.order))) || new Set(existingSteps.map(s => String(s.order))).size !== existingSteps.length || new Set(existingSteps.map(s => stringValue(s.uiUniqueIdentifier || s.ui_unique_identifier))).size !== existingSteps.length) throw new Error('Ambiguous existing step orders or identities');
1431
+ let topTry = existingLogics.find(fl => String(fl.definitionId) === 'e9060aa2c3013010ace8b740ad40dd51');
1432
+ let topCatch = existingLogics.find(fl => String(fl.definitionId) === '35d60003e6022010a5e40cdd1254dd23');
1433
+
1434
+ for (const id of ['e9060aa2c3013010ace8b740ad40dd51', '35d60003e6022010a5e40cdd1254dd23']) {
1435
+ if (existingLogics.filter(fl => String(fl.definitionId) === id).length > 1) throw new Error('Ambiguous existing error handling blocks');
1436
+ }
1437
+ if (Boolean(topTry) !== Boolean(topCatch)) throw new Error('Incomplete existing error handling pair; reconcile in Flow Designer before retrying');
1438
+ if (topTry && (!stringValue(topTry.uiUniqueIdentifier || topTry.ui_unique_identifier) || !stringValue(topCatch.uiUniqueIdentifier || topCatch.ui_unique_identifier) || !Number.isInteger(Number(topCatch.order)))) throw new Error('Malformed existing error handling identities');
1439
+ if (topCatch?.connectedTo && topCatch.connectedTo !== topTry.uiUniqueIdentifier) throw new Error('Existing Catch is connected to a different Try');
1440
+ // 1. Ensure Top Level Try (order 0)
1441
+ let tryUiId = topTry ? stringValue(topTry.uiUniqueIdentifier || topTry.ui_unique_identifier) : '';
1442
+ if (!topTry) {
1443
+ tryUiId = idFactory();
1444
+ const tryDef = FLOW_LOGIC_DEFINITIONS['top level try'];
1445
+ flowLogicInserts.push({
1446
+ order: '0',
1447
+ uiUniqueIdentifier: tryUiId,
1448
+ parent: '',
1449
+ parentUiId: '',
1450
+ connectedTo: '',
1451
+ metadata: '{"predicates":[]}',
1452
+ flowSysId: flowId,
1453
+ generationSource: '',
1454
+ definitionId: tryDef.id,
1455
+ type: 'flowlogic',
1456
+ inputs: [],
1457
+ outputsToAssign: [],
1458
+ flowLogicDefinition: {
1459
+ id: tryDef.id,
1460
+ name: tryDef.name,
1461
+ description: tryDef.description,
1462
+ connectedTo: '',
1463
+ quiescence: 'never',
1464
+ compilationClass: tryDef.compilationClass,
1465
+ order: tryDef.order,
1466
+ type: tryDef.type,
1467
+ visible: true,
1468
+ attributes: tryDef.attributes,
1469
+ userCanRead: true,
1470
+ category: '',
1471
+ inputs: [],
1472
+ variables: '[]'
1473
+ }
1474
+ });
1475
+ changes.push({ component: 'flowLogic', order: 0, type: 'Top Level Try', input: 'insert', before: null, after: { uiUniqueIdentifier: tryUiId } });
1476
+
1477
+ // Re-parent all existing unparented main body actions (order >= 1) to Top Level Try
1478
+ for (const a of existingActions) {
1479
+ if (!a.parent && !a.parentUiId && !actionUpdates.some(u => u.uiUniqueIdentifier === stringValue(a.uiUniqueIdentifier || a.ui_unique_identifier) && u.parent !== undefined)) {
1480
+ const uiId = stringValue(a.uiUniqueIdentifier || a.ui_unique_identifier);
1481
+ actionUpdates.push({
1482
+ uiUniqueIdentifier: uiId,
1483
+ type: 'action',
1484
+ parent: tryUiId,
1485
+ parentUiId: tryUiId
1486
+ });
1487
+ }
1488
+ }
1489
+ // Re-parent all newly inserted actions that lack parent to Top Level Try
1490
+ for (const a of actionInserts) {
1491
+ if (!a.parent) {
1492
+ a.parent = tryUiId;
1493
+ a.parentUiId = tryUiId;
1494
+ }
1495
+ }
1496
+ // Re-parent all unparented logic blocks
1497
+ for (const fl of existingLogics) {
1498
+ if (!fl.parent && String(fl.definitionId) !== '35d60003e6022010a5e40cdd1254dd23') {
1499
+ const uiId = stringValue(fl.uiUniqueIdentifier || fl.ui_unique_identifier);
1500
+ flowLogicUpdates.push({
1501
+ uiUniqueIdentifier: uiId,
1502
+ type: 'flowlogic',
1503
+ parent: tryUiId,
1504
+ parentUiId: tryUiId
1505
+ });
1506
+ }
1507
+ }
1508
+ for (const fl of flowLogicInserts) {
1509
+ if (!fl.parent && fl.definitionId !== 'e9060aa2c3013010ace8b740ad40dd51' && fl.definitionId !== '35d60003e6022010a5e40cdd1254dd23') {
1510
+ fl.parent = tryUiId;
1511
+ fl.parentUiId = tryUiId;
1512
+ }
1513
+ }
1514
+ }
1515
+
1516
+ // New main-body children belong to the Try even on a rerun. Explicit
1517
+ // requested parents are retained.
1518
+ for (const a of actionInserts) if (!a.parent && !a.parentUiId) { a.parent = tryUiId; a.parentUiId = tryUiId; }
1519
+
1520
+ // 2. Ensure Top Level Catch
1521
+ let catchUiId = topCatch ? stringValue(topCatch.uiUniqueIdentifier || topCatch.ui_unique_identifier) : '';
1522
+ // An existing Catch already owns its order; re-running the same manifest must
1523
+ // place error actions after it instead of guessing a fixed slot.
1524
+ let catchOrder = topCatch ? parseInt(topCatch.order, 10) : NaN;
1525
+ if (!topCatch) {
1526
+ catchUiId = idFactory();
1527
+ const catchDef = FLOW_LOGIC_DEFINITIONS['top level catch'];
1528
+ // Determine max order
1529
+ let maxOrder = 0;
1530
+ for (const a of existingActions) maxOrder = Math.max(maxOrder, parseInt(a.order, 10) || 0);
1531
+ for (const fl of existingLogics) maxOrder = Math.max(maxOrder, parseInt(fl.order, 10) || 0);
1532
+ for (const a of actionInserts) maxOrder = Math.max(maxOrder, parseInt(a.order, 10) || 0);
1533
+ for (const fl of flowLogicInserts) maxOrder = Math.max(maxOrder, parseInt(fl.order, 10) || 0);
1534
+ catchOrder = maxOrder + 1;
1535
+
1536
+ flowLogicInserts.push({
1537
+ order: String(catchOrder),
1538
+ uiUniqueIdentifier: catchUiId,
1539
+ parent: '',
1540
+ parentUiId: '',
1541
+ connectedTo: tryUiId,
1542
+ metadata: '{"predicates":[]}',
1543
+ flowSysId: flowId,
1544
+ generationSource: '',
1545
+ definitionId: catchDef.id,
1546
+ type: 'flowlogic',
1547
+ inputs: [
1548
+ { name: 'enabled', value: { schemaless: false, schemalessValue: '', value: 'true' } }
1549
+ ],
1550
+ outputsToAssign: [],
1551
+ flowLogicDefinition: {
1552
+ id: catchDef.id,
1553
+ name: catchDef.name,
1554
+ description: catchDef.description,
1555
+ connectedTo: catchDef.connectedTo,
1556
+ quiescence: 'never',
1557
+ compilationClass: catchDef.compilationClass,
1558
+ order: catchDef.order,
1559
+ type: catchDef.type,
1560
+ visible: true,
1561
+ attributes: catchDef.attributes,
1562
+ userCanRead: true,
1563
+ category: '',
1564
+ inputs: [],
1565
+ variables: '[]'
1566
+ }
1567
+ });
1568
+ changes.push({ component: 'flowLogic', order: catchOrder, type: 'Top Level Catch', input: 'insert', before: null, after: { uiUniqueIdentifier: catchUiId } });
1569
+ }
1570
+
1571
+ // Register Catch step in pendingSteps for data pill resolution
1572
+ pendingSteps.push({
1573
+ name: 'Error Handler',
1574
+ order: String(Number.isFinite(catchOrder) ? catchOrder : existingActions.length + 1),
1575
+ uiUniqueIdentifier: catchUiId,
1576
+ inputs: [
1577
+ { name: '__status__.message', parameter: { label: 'Error Status➛Message', type: 'string' } },
1578
+ { name: '__status__.code', parameter: { label: 'Error Status➛Code', type: 'integer' } }
1579
+ ]
1580
+ });
1581
+
1582
+ // 3. Process errorHandling actions
1583
+ const errorActions = Array.isArray(errorHandlingInput.actions) ? errorHandlingInput.actions : [];
1584
+ const errorPill = name => String(name)
1585
+ .replace(/\{\{error\.message\}\}/g, `{{${catchUiId}.__status__.message}}`)
1586
+ .replace(/\{\{error\.code\}\}/g, `{{${catchUiId}.__status__.code}}`);
1587
+ const children = existingActions.filter(a => a.parent === catchUiId || a.parentUiId === catchUiId).sort((a, b) => Number(a.order) - Number(b.order));
1588
+ if (existingLogics.some(l => l.parent === catchUiId || l.parentUiId === catchUiId)) throw new Error('Ambiguous Catch children include logic blocks');
1589
+ const childOrders = children.map(a => String(a.order));
1590
+ if (new Set(childOrders).size !== childOrders.length || children.some(a => !a.uiUniqueIdentifier || !Number.isInteger(Number(a.order)))) throw new Error('Ambiguous Catch child identities or orders');
1591
+ let errActionOrder = Math.max(catchOrder, ...existingActions.map(a => Number(a.order)), ...existingLogics.map(a => Number(a.order)), ...actionInserts.map(a => Number(a.order)), ...flowLogicInserts.map(a => Number(a.order))) + 1;
1592
+ for (const [eIdx, eAction] of errorActions.entries()) {
1593
+ const resolved = await resolveActionType(sdk, eAction.type);
1594
+ const actionDefinition = await readActionDefinition(sdk, instance, resolved.id, scope);
1595
+ const existingChild = children[eIdx];
1596
+ if (existingChild && actionTypeIdOf(existingChild) !== resolved.id) throw new Error(`Error action ${eIdx + 1} does not match existing Catch child type; ambiguous reconciliation`);
1597
+ const uiUniqueIdentifier = existingChild ? existingChild.uiUniqueIdentifier : idFactory();
1598
+ actionUiMap.set(`error_${eIdx + 1}`, uiUniqueIdentifier);
1599
+ // Resolve the friendly {{error.*}} tokens before the typed inputs are
1600
+ // built: the value that reaches the instance has to name the Catch
1601
+ // instance's own pill, otherwise the canvas stores an unresolved
1602
+ // reference and no labelCache entry can draw it.
1603
+ const errorInputs = Object.fromEntries(Object.entries(eAction.inputs || {})
1604
+ .map(([input, value]) => [input, typeof value === 'string' ? errorPill(value) : value]));
1605
+ if (existingChild) {
1606
+ const update = buildActionUpdate(existingChild, { ...eAction, inputs: errorInputs }, eIdx);
1607
+ actionUpdates.push(update);
1608
+ actionTargets.set(uiUniqueIdentifier, existingChild);
1609
+ changedActionInputs.set(uiUniqueIdentifier, new Set([...(changedActionInputs.get(uiUniqueIdentifier) || []), ...Object.keys(errorInputs)]));
1610
+ for (const [input, after] of Object.entries(errorInputs)) {
1611
+ changes.push({ component: 'errorAction', order: existingChild.order, type: eAction.type, input, before: inputRawValue(inputList(existingChild).find(i => i.name === input)), after });
1612
+ collectPills(after, uiUniqueIdentifier, input);
1613
+ }
1614
+ continue;
1615
+ }
1616
+ const insertInputs = buildTypedInputs({ ...eAction, inputs: errorInputs }, actionDefinition.schema);
1617
+ pendingSteps.push({ name: eAction.type, order: String(errActionOrder), uiUniqueIdentifier, inputs: insertInputs });
1618
+ actionInserts.push({
1619
+ actionTypeSysId: resolved.id,
1620
+ flowSysId: flowId,
1621
+ generationSource: '',
1622
+ type: 'action',
1623
+ order: String(errActionOrder),
1624
+ parent: catchUiId,
1625
+ uiUniqueIdentifier,
1626
+ parentUiId: catchUiId,
1627
+ metadata: JSON.stringify(parseMaybeJson(actionDefinition.definition.metadata, {})),
1628
+ inputs: insertInputs,
1629
+ });
1630
+ changedActionInputs.set(uiUniqueIdentifier, new Set(Object.keys(eAction.inputs || {})));
1631
+ for (const [input, after] of Object.entries(eAction.inputs || {})) {
1632
+ const resolvedVal = typeof after === 'string' ? errorPill(after) : after;
1633
+ changes.push({ component: 'errorAction', order: errActionOrder, type: eAction.type, input, before: null, after: resolvedVal });
1634
+ collectPills(resolvedVal, uiUniqueIdentifier, input);
1635
+ }
1636
+ errActionOrder++;
1637
+ }
1638
+ }
1639
+
1640
+ async function planManifestSteps({ manifest, beforeDefinition, existingActions, existingOrders, actionUiMap, logicUiMap, pendingSteps, idFactory, sdk, instance, scope, flowId, actionInserts, actionUpdates, flowLogicInserts, actionTargets, changedActionInputs, changes, collectPills }) {
1641
+ const existingLogics = beforeDefinition.flowLogicInstances || beforeDefinition.flowLogics || [];
1642
+ const registry = new Map();
1643
+ const byUi = new Map();
1644
+ const register = (step, kind) => {
1645
+ const ui = stringValue(step.uiUniqueIdentifier || step.ui_unique_identifier);
1646
+ const order = String(step.order);
1647
+ if (registry.has(order) && kind === 'action') throw new Error(`Ambiguous step order ${order}: multiple Action instances`);
1648
+ if (!ui || byUi.has(ui) || registry.has(order)) throw new Error(`Ambiguous step identity or order ${order}`);
1649
+ const entry = { ...step, uiUniqueIdentifier: ui, kind };
1650
+ registry.set(order, entry); byUi.set(ui, entry);
1651
+ (kind === 'action' ? actionUiMap : logicUiMap).set(order, ui);
1652
+ return entry;
1653
+ };
1654
+ const rawDeletes = manifest.deleteSteps || manifest.delete || manifest.deleteOrders || [];
1655
+ const deleteTargets = new Set((Array.isArray(rawDeletes) ? rawDeletes : [rawDeletes]).map(String));
1656
+ const isDeleted = step => {
1657
+ const ui = stringValue(step.uiUniqueIdentifier || step.ui_unique_identifier);
1658
+ const id = stringValue(step.sysId || step.id || step.sys_id || ui);
1659
+ return [String(step.order), ui, id].some(value => deleteTargets.has(value));
1660
+ };
1661
+ const deletedUis = new Set();
1662
+ for (const step of [...existingActions, ...existingLogics]) {
1663
+ if (!isDeleted(step)) continue;
1664
+ deletedUis.add(stringValue(step.uiUniqueIdentifier || step.ui_unique_identifier));
1665
+ actionUiMap.delete(String(step.order));
1666
+ logicUiMap.delete(String(step.order));
1667
+ }
1668
+ existingActions = existingActions.filter(step => !isDeleted(step));
1669
+ existingOrders = new Set(existingActions.map(step => String(step.order)));
1670
+ for (const step of existingActions) register(step, 'action');
1671
+ for (const step of existingLogics.filter(step => !isDeleted(step))) register(step, 'logic');
1672
+ const logicSpecs = manifest.flowLogics || manifest.logic || [];
1673
+ for (const l of logicSpecs) {
1674
+ const type = String(l.type || l.name).toLowerCase().trim();
1675
+ register({ ...l, definitionId: FLOW_LOGIC_DEFINITIONS[type].id, uiUniqueIdentifier: idFactory() }, 'logic');
1676
+ }
1677
+ const actionPlans = new Map();
1678
+ for (const [index, a] of (manifest.actions || []).entries()) {
1679
+ if (actionPlans.has(String(a.order))) throw new Error(`Duplicate action update for order ${a.order}`);
1680
+ if (existingOrders.has(String(a.order))) { actionPlans.set(String(a.order), { existing: true }); continue; }
1681
+ const resolved = await resolveActionType(sdk, a.type);
1682
+ const actionDefinition = await readActionDefinition(sdk, instance, resolved.id, scope);
1683
+ const uiUniqueIdentifier = idFactory();
1684
+ const entry = register({ ...a, uiUniqueIdentifier }, 'action');
1685
+ // Schemas exist before any value is resolved, including forward references.
1686
+ pendingSteps.push({ ...entry, name: a.type, inputs: buildTypedInputs(a, actionDefinition.schema) });
1687
+ actionPlans.set(String(a.order), { resolved, actionDefinition, uiUniqueIdentifier, index });
1688
+ }
1689
+ const resolveLink = (values, label, owner) => {
1690
+ const supplied = values.filter(v => v !== undefined);
1691
+ if (!supplied.length) return '';
1692
+ const targets = supplied.map(v => {
1693
+ const target = registry.get(String(v)) || byUi.get(String(v));
1694
+ if (!target || target.kind !== 'logic' || target.uiUniqueIdentifier === owner) throw new Error(`Absent, wrong-type or self ${label} target ${v}`);
1695
+ return target;
1696
+ });
1697
+ if (new Set(targets.map(t => t.uiUniqueIdentifier)).size !== 1) throw new Error(`Conflicting ${label} aliases`);
1698
+ const target = targets[0];
1699
+ if (label === 'Catch' && !['07223332de022010ec58424b73829721', 'e9060aa2c3013010ace8b740ad40dd51'].includes(target.definitionId)) throw new Error('Catch target must be a Try block');
1700
+ if (label === 'parent' && !Object.values(FLOW_LOGIC_DEFINITIONS).some(d => d.id === target.definitionId && /^(TRY|TOP_LEVEL_TRY|CATCH|TOP_LEVEL_CATCH|IF|ELSE|ELSEIF)$/.test(d.type))) throw new Error('Parent target cannot contain children');
1701
+ return target.uiUniqueIdentifier;
1702
+ };
1703
+ for (const l of logicSpecs) {
1704
+ const entry = registry.get(String(l.order));
1705
+ entry.resolvedParent = resolveLink([l.parent, l.parentOrder, l.parentUiId], 'parent', entry.uiUniqueIdentifier);
1706
+ }
1707
+ for (const entry of registry.values()) {
1708
+ const seen = new Set([entry.uiUniqueIdentifier]);
1709
+ let parent = entry.resolvedParent || entry.parentUiId || entry.parent;
1710
+ while (parent && byUi.has(String(parent))) {
1711
+ if (seen.has(parent)) throw new Error('Cyclic parent links');
1712
+ seen.add(parent); const next = byUi.get(parent); parent = next.resolvedParent || next.parentUiId || next.parent;
1713
+ }
1714
+ }
1715
+
1716
+ // Handle flowLogics insertion and update
1717
+ const requestedLogics = manifest.flowLogics || manifest.logic || [];
1718
+ const logicTypeKey = t => String(t || '').toLowerCase().trim();
1719
+ // A manifest names steps by order ({{step_4.__status__.message}} or
1720
+ // {{4.message}}). Resolve that only once the owning map entry exists, but do
1721
+ // it before any value is packaged: a token that survives into the payload
1722
+ // stores an unresolvable reference the canvas renders blank.
1723
+ const resolveStepPill = value => {
1724
+ for (const match of String(value).matchAll(/\{\{([^}]+)\}\}/g)) {
1725
+ if ([...deletedUis].some(ui => match[1].startsWith(`${ui}.`))) throw new Error(`Absent deleted step reference ${match[0]}`);
1726
+ }
1727
+ return String(value).replace(/\{\{(?:step_)?(\d+)\.([^}]+)\}\}/g, (match, order, field) => {
1728
+ const ui = actionUiMap.get(String(order)) || logicUiMap.get(String(order));
1729
+ if (!ui) throw new Error(`Absent step reference ${match}`);
1730
+ return `{{${ui}.${field}}}`;
1731
+ });
1732
+ };
1733
+ const resolveStepValue = value => {
1734
+ if (typeof value === 'string') return resolveStepPill(value);
1735
+ if (Array.isArray(value)) return value.map(resolveStepValue);
1736
+ if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, resolveStepValue(v)]));
1737
+ return value;
1738
+ };
1739
+ const resolveStepInputs = inputs => resolveStepValue(inputs || {});
1740
+
1741
+ for (const [logicIdx, l] of requestedLogics.entries()) {
1742
+ const lType = logicTypeKey(l.type || l.name);
1743
+ const logicDef = FLOW_LOGIC_DEFINITIONS[lType] || {
1744
+ id: l.definitionId || l.id || '',
1745
+ name: l.name || l.type,
1746
+ type: (l.type || '').toUpperCase(),
1747
+ description: '',
1748
+ compilationClass: '',
1749
+ order: l.order || logicIdx + 1,
1750
+ connectedTo: l.connectedTo || '',
1751
+ attributes: 'allow_children=true,allow_siblings=true,'
1752
+ };
1753
+
1754
+ const uiUniqueIdentifier = logicUiMap.get(String(l.order));
1755
+ const parentUiId = resolveLink([l.parent, l.parentOrder, l.parentUiId], 'parent', uiUniqueIdentifier);
1756
+ const connectedTo = resolveLink([l.connectedTo, l.connectedToOrder], /catch$/.test(lType) ? 'Catch' : 'connection', uiUniqueIdentifier);
1757
+ // A Catch only works when it points at one specific Try instance. Falling
1758
+ // back to the definition id writes a link the instance cannot resolve, so
1759
+ // demand the pairing instead of guessing it.
1760
+ if ((lType === 'catch' || lType === 'top level catch') && l.connectedTo === undefined && l.connectedToOrder === undefined) {
1761
+ throw new Error(`Flow logic at order ${l.order} is a Catch block; set connectedToOrder to the Try block's order so the pair stays linked`);
1762
+ }
1763
+
1764
+ let resolvedCondition = resolveStepPill(l.condition || '');
1765
+
1766
+ const inputs = [];
1767
+ collectPills(resolvedCondition, uiUniqueIdentifier, 'condition');
1768
+
1769
+ if (lType === 'if' || lType === 'else if') {
1770
+ inputs.push({
1771
+ name: 'condition_name',
1772
+ value: { schemaless: false, schemalessValue: '', value: l.condition_name || l.conditionName || l.label || '' }
1773
+ });
1774
+ inputs.push({
1775
+ name: 'condition',
1776
+ value: { schemaless: false, schemalessValue: '', value: resolvedCondition }
1777
+ });
1778
+ } else if (lType === 'catch' || lType === 'top level catch') {
1779
+ inputs.push({
1780
+ name: 'enabled',
1781
+ value: { schemaless: false, schemalessValue: '', value: 'true' }
1782
+ });
1783
+ }
1784
+
1785
+ const flowVarsArray = [];
1786
+ if (lType === 'set flow variables' && l.values) {
1787
+ for (const [varName, varVal] of Object.entries(l.values)) {
1788
+ const resolvedValue = resolveStepValue(varVal);
1789
+ collectPills(resolvedValue, uiUniqueIdentifier, varName);
1790
+ flowVarsArray.push({
1791
+ id: '',
1792
+ name: varName,
1793
+ children: [],
1794
+ displayValue: { value: '' },
1795
+ value: { schemaless: false, schemalessValue: '', value: resolvedValue }
1796
+ });
1797
+ }
1798
+ }
1799
+
1800
+ flowLogicInserts.push({
1801
+ order: String(l.order || logicIdx + 1),
1802
+ uiUniqueIdentifier,
1803
+ parent: parentUiId,
1804
+ parentUiId,
1805
+ connectedTo,
1806
+ metadata: '{"predicates":[]}',
1807
+ flowSysId: flowId,
1808
+ generationSource: '',
1809
+ definitionId: logicDef.id,
1810
+ type: 'flowlogic',
1811
+ inputs,
1812
+ outputsToAssign: [],
1813
+ ...(flowVarsArray.length ? { flowVariables: flowVarsArray } : {}),
1814
+ flowLogicDefinition: {
1815
+ id: logicDef.id,
1816
+ name: logicDef.name,
1817
+ description: logicDef.description,
1818
+ connectedTo: logicDef.connectedTo,
1819
+ quiescence: 'never',
1820
+ compilationClass: logicDef.compilationClass,
1821
+ order: logicDef.order,
1822
+ type: logicDef.type,
1823
+ visible: true,
1824
+ attributes: logicDef.attributes,
1825
+ userCanRead: true,
1826
+ category: '',
1827
+ inputs: [],
1828
+ variables: '[]'
1829
+ }
1830
+ });
1831
+
1832
+ if (lType === 'catch' || lType === 'top level catch') {
1833
+ pendingSteps.push({
1834
+ name: 'Catch',
1835
+ order: String(l.order || logicIdx + 1),
1836
+ uiUniqueIdentifier,
1837
+ inputs: [
1838
+ { name: '__status__.message', parameter: { label: 'Error Status➛Message', type: 'string' } },
1839
+ { name: '__status__.code', parameter: { label: 'Error Status➛Code', type: 'integer' } }
1840
+ ]
1841
+ });
1842
+ }
1843
+
1844
+ changes.push({ component: 'flowLogic', order: l.order, type: logicDef.name, input: 'insert', before: null, after: { parent: parentUiId, connectedTo } });
1845
+ }
1846
+
1847
+ for (const [index, requested] of (manifest.actions || []).entries()) {
1848
+ const isInsert = !existingOrders.has(String(requested.order));
1849
+ if (isInsert) {
1850
+ const { resolved, actionDefinition, uiUniqueIdentifier } = actionPlans.get(String(requested.order));
1851
+ actionUiMap.set(String(requested.order), uiUniqueIdentifier);
1852
+ // Resolve before packaging: the instance must receive the producing step's
1853
+ // own pill name, not the order-based token from the manifest.
1854
+ const insertInputs = buildTypedInputs({ ...requested, inputs: resolveStepInputs(requested.inputs) }, actionDefinition.schema);
1855
+ // A later step in this same manifest may reference this one; its identity
1856
+ // and schema exist now even though the flow does not carry it yet.
1857
+ Object.assign(pendingSteps.find(s => s.uiUniqueIdentifier === uiUniqueIdentifier), { inputs: insertInputs });
1858
+ const actParent = resolveLink([requested.parentUiId, requested.parentOrder, requested.parent], 'parent', uiUniqueIdentifier);
1859
+ actionInserts.push({
1860
+ actionTypeSysId: resolved.id,
1861
+ flowSysId: flowId,
1862
+ generationSource: '',
1863
+ type: 'action',
1864
+ order: String(requested.order),
1865
+ parent: actParent,
1866
+ uiUniqueIdentifier,
1867
+ parentUiId: actParent,
1868
+ metadata: JSON.stringify(parseMaybeJson(actionDefinition.definition.metadata, {})),
1869
+ inputs: insertInputs,
1870
+ });
1871
+ changedActionInputs.set(uiUniqueIdentifier, new Set(Object.keys(requested.inputs || {})));
1872
+ for (const [input, after] of Object.entries(requested.inputs || {})) {
1873
+ const resolvedAfter = typeof after === 'string' ? resolveStepPill(after) : after;
1874
+ changes.push({ component: 'action', order: requested.order, type: requested.type, input, before: null, after: resolvedAfter });
1875
+ collectPills(resolvedAfter, uiUniqueIdentifier, input);
1876
+ }
1877
+ } else {
1878
+ const existing = await resolveExistingAction(sdk, existingActions, requested, index);
1879
+ const resolvedRequest = { ...requested, inputs: resolveStepInputs(requested.inputs) };
1880
+ const update = buildActionUpdate(existing, resolvedRequest, index);
1881
+ if (['parent', 'parentOrder', 'parentUiId'].some(k => requested[k] !== undefined)) {
1882
+ const parent = resolveLink([requested.parentUiId, requested.parentOrder, requested.parent], 'parent', existing.uiUniqueIdentifier);
1883
+ update.parent = parent; update.parentUiId = parent;
1884
+ }
1885
+ actionUpdates.push(update);
1886
+ const uiId = stringValue(existing.uiUniqueIdentifier || existing.ui_unique_identifier);
1887
+ if (actionTargets.has(uiId)) throw new Error(`Duplicate action update for order ${requested.order}; combine input changes in one action entry`);
1888
+ actionTargets.set(uiId, existing);
1889
+ changedActionInputs.set(uiId, new Set(Object.keys(requested.inputs)));
1890
+ for (const [input, after] of Object.entries(requested.inputs)) {
1891
+ const resolvedAfter = typeof after === 'string' ? resolveStepPill(after) : after;
1892
+ changes.push({ component: 'action', order: requested.order, type: requested.type, input, before: inputRawValue(inputList(existing).find(field => field.name === input)), after: resolvedAfter });
1893
+ collectPills(resolvedAfter, uiId, input);
1894
+ }
1895
+ }
1896
+ }
1897
+
1898
+ }
1899
+
1235
1900
  export async function createFlowFromManifest(sdk, instance, inputManifest, options = {}) {
1236
1901
  const manifest = validateFlowManifest(inputManifest);
1237
1902
  const scope = manifest.scope;
@@ -1245,6 +1910,27 @@ export async function createFlowFromManifest(sdk, instance, inputManifest, optio
1245
1910
  throw new Error(`Flow creation refused before any content write: capture context could not be established. ${error.message}`, { cause: error });
1246
1911
  }
1247
1912
 
1913
+ const actionInstances = [];
1914
+ const flowLogicInserts = [];
1915
+ const labelCacheInserts = [];
1916
+ const pendingSteps = [];
1917
+ const pills = [];
1918
+ const collectPills = (value, uiUniqueIdentifier, inputName) => {
1919
+ for (const match of String(value).matchAll(/\{\{([^}]+)\}\}/g)) pills.push({ name: match[1], uiUniqueIdentifier, inputName });
1920
+ };
1921
+ const orderedManifest = { ...manifest, actions: manifest.actions.map((a, index) => ({ ...a, order: a.order ?? index + 1, inputs: a.inputs || {} })) };
1922
+ await planManifestSteps({ manifest: orderedManifest, beforeDefinition: {}, existingActions: [], existingOrders: new Set(), actionUiMap: new Map(), logicUiMap: new Map(), pendingSteps, idFactory, sdk, instance, scope, flowId: '', actionInserts: actionInstances, actionUpdates: [], flowLogicInserts, actionTargets: new Map(), changedActionInputs: new Map(), changes: [], collectPills });
1923
+ if (manifest.errorHandling !== undefined) await planErrorHandling({ sdk, instance, scope, flowId: '', beforeDefinition: {}, existingActions: [], actionInserts: actionInstances, actionUpdates: [], flowLogicInserts, flowLogicUpdates: [], changes: [], idFactory, actionUiMap: new Map(), pendingSteps, changedActionInputs: new Map(), collectPills, errorHandlingInput: manifest.errorHandling });
1924
+ for (const pill of pills) {
1925
+ const binding = resolvePillBinding({}, pill.name, '', [], pendingSteps);
1926
+ const previous = labelCacheInserts.find(e => e.name === pill.name);
1927
+ if (previous) {
1928
+ if (!previous.usedInstances.some(i => i.uiUniqueIdentifier === pill.uiUniqueIdentifier && i.inputName === pill.inputName)) previous.usedInstances.push({ uiUniqueIdentifier: pill.uiUniqueIdentifier, inputName: pill.inputName });
1929
+ } else labelCacheInserts.push(labelCacheEntry({ name: pill.name, label: binding.label, type: binding.type, baseType: binding.type, usedInstances: { [pill.uiUniqueIdentifier]: [pill.inputName] } }));
1930
+ }
1931
+
1932
+ validateFinalStepPlan({}, actionInstances, [], [], flowLogicInserts, [], []);
1933
+
1248
1934
  let parentResponse;
1249
1935
  try {
1250
1936
  parentResponse = await mutationContext('parent_create', readUpdateSet, snapshots, () => sdk.request(`${instance}${FLOW_ENDPOINT}?param_only_properties=true&sysparm_transaction_scope=${encodeURIComponent(scope)}`, {
@@ -1270,27 +1956,12 @@ export async function createFlowFromManifest(sdk, instance, inputManifest, optio
1270
1956
  const definition = await resolveTriggerDefinition(sdk, manifest.trigger.type);
1271
1957
  const trigger = await buildCreateTrigger(sdk, flowId, manifest, definition, options);
1272
1958
 
1273
- const actionInstances = [];
1274
- for (const [index, action] of manifest.actions.entries()) {
1275
- const resolved = await resolveActionType(sdk, action.type);
1276
- const actionDefinition = await readActionDefinition(sdk, instance, resolved.id, scope);
1277
- actionInstances.push({
1278
- actionTypeSysId: resolved.id,
1279
- flowSysId: flowId,
1280
- generationSource: '',
1281
- type: 'action',
1282
- order: String(index + 1),
1283
- parent: '',
1284
- uiUniqueIdentifier: idFactory(),
1285
- parentUiId: '',
1286
- metadata: JSON.stringify(parseMaybeJson(actionDefinition.definition.metadata, {})),
1287
- inputs: buildTypedInputs(action, actionDefinition.schema),
1288
- });
1289
- }
1959
+ for (const action of actionInstances) action.flowSysId = flowId;
1960
+ for (const logic of flowLogicInserts) logic.flowSysId = flowId;
1290
1961
 
1291
1962
  const patchResponse = await mutationContext('trigger_and_actions_patch', readUpdateSet, snapshots, () => sdk.request(`${instance}${GRAPHQL_ENDPOINT}`, {
1292
1963
  method: 'POST',
1293
- body: JSON.stringify({ query: buildFlowPatchMutation({ flowId, trigger, actions: actionInstances }), variables: {} }),
1964
+ body: JSON.stringify({ query: buildFlowPatchMutation({ flowId, trigger, actions: actionInstances, flowLogicInserts, labelCacheInserts }), variables: {} }),
1294
1965
  }), updateSet => readUpdateSetCapture(sdk, updateSet, flowId));
1295
1966
  assertGraphQLSuccess(patchResponse, 'Flow trigger/action patch');
1296
1967
  const insertedTrigger = insertedTriggers(patchResponse)[0];
@@ -1316,6 +1987,10 @@ export async function createFlowFromManifest(sdk, instance, inputManifest, optio
1316
1987
  const processflow = await readProcessFlow(sdk, instance, flowId, scope);
1317
1988
  verifyCreatedFlowReadback({ flowId, processflow, trigger, insertedTrigger, manifest, actionInstances, inserted, stageInserts });
1318
1989
  assertStagesPlaced(processflow, stageInserts, flowId);
1990
+ assertInsertedIdentities(patchResponse, processflow, flowLogicInserts, 'logic', flowId);
1991
+ assertStepReadback(processflow, actionInstances, 'action', flowId);
1992
+ assertStepReadback(processflow, flowLogicInserts, 'logic', flowId);
1993
+ for (const entry of labelCacheInserts) if (!readLabelCache(processflow).some(e => e.name === entry.name && e.label)) throw new Error(`Flow ${flowId} did not persist data pill ${entry.name}`);
1319
1994
  const { version } = await mutationContext('autosave_version', readUpdateSet, snapshots, () => createVerifiedFlowVersion(sdk, {
1320
1995
  instance, flowId, scope, type: 'Autosave', annotation: 'JSN flow create',
1321
1996
  }), updateSet => readUpdateSetCapture(sdk, updateSet, flowId));
@@ -1333,7 +2008,7 @@ export async function createFlowFromManifest(sdk, instance, inputManifest, optio
1333
2008
  ...(captureContext ? { capture_context: captureContext } : {}),
1334
2009
  update_set_capture: updateSetCapture,
1335
2010
  update_set_mutations: snapshots,
1336
- lifecycle: { published: false, supported: ['draft', 'autosave'], deferred: ['publish/activation', 'Flow Logic', 'subflows', 'flow variables', 'error handling'] },
2011
+ lifecycle: { published: false, supported: ['draft', 'autosave'], deferred: ['publish/activation', 'subflows', 'flow variables'] },
1337
2012
  };
1338
2013
  } catch (error) {
1339
2014
  // Creation is two-stage: the parent POST leaves a real draft behind when the
@@ -1403,7 +2078,8 @@ export function resolvePillBinding(definition, pillName, flowId, cache, pending
1403
2078
  const separator = pillName.indexOf('.');
1404
2079
  if (separator <= 0) return fail();
1405
2080
  const stepKey = pillName.slice(0, separator);
1406
- const fieldName = pillName.slice(separator + 1).split('.')[0];
2081
+ const remainder = pillName.slice(separator + 1);
2082
+ const fieldName = remainder.startsWith('__status__.') ? remainder : remainder.split('.')[0];
1407
2083
  const describe = (fields, name) => {
1408
2084
  const field = inputList({ inputs: fields }).find(entry => stringValue(entry?.name) === name);
1409
2085
  if (!field) return null;
@@ -1417,6 +2093,16 @@ export function resolvePillBinding(definition, pillName, flowId, cache, pending
1417
2093
  ...findArray(definition, 'triggerInstances').map(step => ({ ...step, trigger: true })),
1418
2094
  ...findExistingActions(definition).map(step => ({ ...step, trigger: false })),
1419
2095
  ...pending.map(step => ({ ...step, trigger: false })),
2096
+ ...(findArray(definition, 'flowLogicInstances') || []).filter(fl => String(fl.definitionId) === '35d60003e6022010a5e40cdd1254dd23' || String(fl.definitionId) === '35d60003e6022010a5e40cdd1254dd21').map(fl => ({
2097
+ name: String(fl.definitionId) === '35d60003e6022010a5e40cdd1254dd23' ? 'Error Handler' : 'Catch',
2098
+ order: stringValue(fl.order),
2099
+ uiUniqueIdentifier: stringValue(fl.uiUniqueIdentifier || fl.ui_unique_identifier),
2100
+ trigger: false,
2101
+ inputs: [
2102
+ { name: '__status__.message', parameter: { label: 'Error Status➛Message', type: 'string' } },
2103
+ { name: '__status__.code', parameter: { label: 'Error Status➛Code', type: 'integer' } }
2104
+ ]
2105
+ }))
1420
2106
  ];
1421
2107
  for (const step of candidates) {
1422
2108
  const name = stringValue(step.name);
@@ -1504,6 +2190,7 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1504
2190
  const pillToInstances = new Map();
1505
2191
  const pendingSteps = [];
1506
2192
  const actionUiMap = new Map();
2193
+ const logicUiMap = new Map(); // order -> uiUniqueIdentifier
1507
2194
  for (const a of existingActions) {
1508
2195
  const ui = stringValue(a.uiUniqueIdentifier || a.ui_unique_identifier);
1509
2196
  if (a.order && ui) actionUiMap.set(String(a.order), ui);
@@ -1522,48 +2209,7 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1522
2209
  }
1523
2210
  };
1524
2211
 
1525
- for (const [index, requested] of (manifest.actions || []).entries()) {
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
- }
1566
- }
2212
+ await planManifestSteps({ manifest, beforeDefinition, existingActions, existingOrders, actionUiMap, logicUiMap, pendingSteps, idFactory, sdk, instance, scope, flowId, actionInserts, actionUpdates, flowLogicInserts, actionTargets, changedActionInputs, changes, collectPills });
1567
2213
 
1568
2214
  const savedStages = stageList(beforeDefinition);
1569
2215
  const savedStageById = new Map(savedStages.map(stage => [stringValue(stage.stageId || stage.stage_id), stage]));
@@ -1638,96 +2284,6 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1638
2284
  changes.push({ component: 'flowVariable', input: name, before: null, after: { label, type, order: varOrder } });
1639
2285
  }
1640
2286
 
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
2287
  // Handle deletions by step order or uiUniqueIdentifier
1732
2288
  const rawDeletes = manifest.deleteSteps || manifest.delete || manifest.deleteOrders || [];
1733
2289
  const deleteTargets = new Set((Array.isArray(rawDeletes) ? rawDeletes : [rawDeletes]).map(String));
@@ -1750,23 +2306,31 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1750
2306
  }
1751
2307
  }
1752
2308
  }
2309
+ const errorHandlingInput = manifest.errorHandling ?? manifest.errorHandler;
2310
+ if (errorHandlingInput !== undefined) await planErrorHandling({ sdk, instance, scope, flowId, beforeDefinition, existingActions, actionInserts, actionUpdates, flowLogicInserts, flowLogicUpdates, changes, idFactory, actionUiMap, pendingSteps, changedActionInputs, collectPills, errorHandlingInput, actionTargets });
2311
+
2312
+ const mergedActionUpdates = new Map();
2313
+ for (const update of actionUpdates) {
2314
+ const prior = mergedActionUpdates.get(update.uiUniqueIdentifier);
2315
+ if (prior) {
2316
+ for (const key of ['parent', 'parentUiId']) if (prior[key] !== undefined && update[key] !== undefined && prior[key] !== update[key]) throw new Error(`Conflicting action ${key} requests`);
2317
+ const inputs = [...(prior.inputs || [])];
2318
+ for (const input of update.inputs || []) {
2319
+ const existing = inputs.find(i => i.name === input.name);
2320
+ if (existing && !isDeepStrictEqual(existing, input)) throw new Error(`Conflicting action input ${input.name} requests`);
2321
+ if (!existing) inputs.push(input);
2322
+ }
2323
+ Object.assign(prior, update, inputs.length ? { inputs } : {});
2324
+ } else mergedActionUpdates.set(update.uiUniqueIdentifier, { ...update });
2325
+ }
2326
+ actionUpdates.splice(0, actionUpdates.length, ...mergedActionUpdates.values());
2327
+
1753
2328
  // Register every referenced pill so the canvas can draw it. Runs after every
1754
2329
  // collection point (actions and logic blocks) so no reference is missed.
1755
2330
  // Existing entries keep their label/type; a pill this flow has never seen gets
1756
2331
  // a label resolved from its producing step.
1757
2332
  const labelCacheInserts = [];
1758
2333
  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
2334
  const mergeUsedInstances = (existing, instances) => {
1771
2335
  const merged = { ...(existing || {}) };
1772
2336
  for (const { uiUniqueIdentifier, inputName } of instances) {
@@ -1798,6 +2362,7 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1798
2362
  labelCacheInserts.push(labelCacheEntry({ name: pillName, label: binding.label, type: binding.type, baseType: binding.type, usedInstances }));
1799
2363
  }
1800
2364
  }
2365
+ validateFinalStepPlan(beforeDefinition, actionInserts, actionUpdates, actionDeletes, flowLogicInserts, flowLogicUpdates, flowLogicDeletes);
1801
2366
  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`);
1802
2367
  if (options.preview) return {
1803
2368
  preview: true,
@@ -1871,6 +2436,11 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1871
2436
  assertGraphQLSuccess(patchResponse, 'Flow trigger/action update');
1872
2437
  completedStage = 'patch_acknowledged';
1873
2438
  const processflow = await readProcessFlow(sdk, instance, flowId, scope);
2439
+ assertInsertedIdentities(patchResponse, processflow, actionInserts, 'action', flowId);
2440
+ assertInsertedIdentities(patchResponse, processflow, flowLogicInserts, 'logic', flowId);
2441
+ assertStepReadback(processflow, [...actionInserts, ...actionUpdates], 'action', flowId);
2442
+ assertStepReadback(processflow, [...flowLogicInserts, ...flowLogicUpdates], 'logic', flowId);
2443
+ assertLogicPreserved(beforeDefinition, processflow, flowLogicInserts, flowLogicUpdates, flowLogicDeletes, flowId);
1874
2444
  // Only requested values may differ. Preserve array order and opaque fields.
1875
2445
  // `stages` is compared separately below: a stage edit may touch specific
1876
2446
  // fields, while every stage the manifest did not name must stay identical.
@@ -1907,6 +2477,12 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1907
2477
  })
1908
2478
  .map(action => {
1909
2479
  const copy = clone(action);
2480
+ const move = actionUpdates.find(update => update.uiUniqueIdentifier === stringValue(action.uiUniqueIdentifier || action.ui_unique_identifier) && update.parent !== undefined);
2481
+ if (move) {
2482
+ if (isAfter && (copy.parent !== move.parent || copy.parentUiId !== move.parentUiId)) throw new Error(`Flow ${flowId} action parent readback did not match requested target`);
2483
+ delete copy.parent;
2484
+ delete copy.parentUiId;
2485
+ }
1910
2486
  const changed = changedActionInputs.get(stringValue(action.uiUniqueIdentifier || action.ui_unique_identifier));
1911
2487
  for (const [index, input] of inputList(copy).entries()) if (changed?.has(input.name)) inputList(copy)[index] = maskInputValue(input);
1912
2488
  return copy;
@@ -1970,7 +2546,7 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1970
2546
  const afterInput = inputList(readback).find(candidate => candidate.name === input.name);
1971
2547
  if (!afterInput) throw new Error(`Flow ${flowId} Action ${uiId} lost input ${input.name} during update`);
1972
2548
  if (!changed.has(input.name) && JSON.stringify(input) !== JSON.stringify(afterInput)) throw new Error(`Flow ${flowId} Action ${uiId} changed omitted input ${input.name}`);
1973
- if (changed.has(input.name) && inputRawValue(afterInput) !== inputRawValue(update.inputs.find(candidate => candidate.name === input.name))) throw new Error(`Flow ${flowId} Action ${uiId} input ${input.name} did not match the requested value`);
2549
+ if (changed.has(input.name) && !isDeepStrictEqual(inputRawValue(afterInput), inputRawValue(update.inputs.find(candidate => candidate.name === input.name)))) throw new Error(`Flow ${flowId} Action ${uiId} input ${input.name} did not match the requested value; preservation failed`);
1974
2550
  }
1975
2551
  }
1976
2552
  completedStage = 'definition_verified';