@jacebenson/jsn 5.5.1-dev.158.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 +143 -4
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jacebenson/jsn",
3
- "version": "5.5.1-dev.158.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`);
@@ -244,6 +246,80 @@ function stageValueFromLabel(label) {
244
246
  * stage, an entry with one edits the stage it names.
245
247
  */
246
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
+
247
323
  export function validateStages(stages, { update = false } = {}) {
248
324
  if (!Array.isArray(stages)) throw new Error('Flow stages must be an array');
249
325
  for (const [index, stage] of stages.entries()) {
@@ -814,7 +890,7 @@ async function resolveExistingAction(sdk, actions, requested, index) {
814
890
 
815
891
  export function validateFlowUpdateManifest(manifest) {
816
892
  if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) throw new Error('Flow update manifest must be a JSON object');
817
- const allowed = new Set(['scope', 'trigger', 'actions', 'stages', 'flowVariables', 'variables', 'flowLogics', 'logic', 'deleteSteps', 'delete', 'deleteOrders']);
893
+ const allowed = new Set(['scope', 'trigger', 'actions', 'stages', 'stageTemplate', 'stageSet', 'flowVariables', 'variables', 'flowLogics', 'logic', 'deleteSteps', 'delete', 'deleteOrders']);
818
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`);
819
895
  if (manifest.scope !== undefined && !String(manifest.scope).trim()) throw new Error('Flow update scope must not be empty');
820
896
  if (manifest.trigger !== undefined) {
@@ -836,8 +912,15 @@ export function validateFlowUpdateManifest(manifest) {
836
912
  if (Object.keys(action.inputs).length === 0) throw new Error(`Update action ${index + 1} inputs must contain at least one changed value`);
837
913
  }
838
914
  }
839
- if (manifest.trigger === undefined && manifest.actions === undefined && manifest.stages === 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');
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');
840
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
+ }
841
924
  return manifest;
842
925
  }
843
926
 
@@ -1217,7 +1300,11 @@ export async function createFlowFromManifest(sdk, instance, inputManifest, optio
1217
1300
 
1218
1301
  // Stages carry componentIndexes that name flow-step orders, so placement
1219
1302
  // runs after the actions exist — the same order Flow Designer uses.
1220
- 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 });
1221
1308
  if (stageInserts.length) {
1222
1309
  const stageResponse = await mutationContext('stage_placement', readUpdateSet, snapshots, () => sdk.request(`${instance}${GRAPHQL_ENDPOINT}`, {
1223
1310
  method: 'POST',
@@ -1388,7 +1475,12 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1388
1475
  const flowLogicUpdates = [];
1389
1476
  const flowLogicDeletes = [];
1390
1477
  const labelCacheUpdates = [];
1391
- const stageInserts = buildStageInserts((manifest.stages || []).filter(stage => stage.stageId === undefined), { idFactory: options.idFactory || (() => randomUUID()), flowId });
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 });
1392
1484
  const stageUpdates = buildStageUpdates((manifest.stages || []).filter(stage => stage.stageId !== undefined));
1393
1485
  const changedActionInputs = new Map();
1394
1486
  const actionTargets = new Map();
@@ -1475,6 +1567,15 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1475
1567
 
1476
1568
  const savedStages = stageList(beforeDefinition);
1477
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
+ }
1478
1579
  for (const update of stageUpdates) {
1479
1580
  const before = savedStageById.get(update.stageId);
1480
1581
  if (!before) throw new Error(`Flow ${flowId} has no stage ${update.stageId}; omit stageId to insert a new stage`);
@@ -1724,6 +1825,44 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1724
1825
  const outcome = await withFlowSafeEdit(sdk, instance, flowId, beforeDefinition.updated, async () => {
1725
1826
  let completedStage = 'validated';
1726
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
+ }
1727
1866
  const patchQuery = buildFlowUpdateMutation({ flowId, triggerUpdates, actionUpdates, actionInserts, actionDeletes, flowVariableInserts, flowLogicInserts, flowLogicUpdates, flowLogicDeletes, labelCacheUpdates, labelCacheInserts, stageInserts, stageUpdates });
1728
1867
  const patchResponse = await mutationContext('trigger_and_actions_update', readUpdateSet, snapshots, () => sdk.request(`${instance}${GRAPHQL_ENDPOINT}`, {
1729
1868
  method: 'POST',