@jacebenson/jsn 5.4.0-dev.150.1 → 5.4.0-dev.152.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jacebenson/jsn",
3
- "version": "5.4.0-dev.150.1",
3
+ "version": "5.4.0-dev.152.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": {
@@ -1,5 +1,6 @@
1
1
  import { parseArgs } from 'node:util';
2
2
  import process from 'node:process';
3
+ import { renderSubcommandHelp } from './help.js';
3
4
 
4
5
  const camel = (name) => name.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
5
6
  const names = (x) => typeof x === 'string' ? [x] : (x || []);
@@ -331,18 +332,66 @@ export class LocalCLI {
331
332
  });
332
333
  }
333
334
 
335
+ /**
336
+ * Usage line for a command page, derived from the node's own declared
337
+ * command. Subcommand pages printed only the path (`Usage: jsn flows`,
338
+ * `Usage: jsn flows show`), which hid the positionals the command accepts and
339
+ * never mentioned options at all.
340
+ */
341
+ _usageLine(node, path, hasChildren) {
342
+ if (node.usageText) return node.usageText;
343
+ const declared = (node.definition.command || '').trim().split(/\s+/).slice(1)
344
+ .filter((token) => !(hasChildren && /^\[sub-?commands?\]$/i.test(token)));
345
+ const parts = [this.script, ...path, ...(hasChildren ? ['<command>'] : []), ...declared, '[options]'];
346
+ return `Usage: ${parts.join(' ')}`;
347
+ }
348
+
349
+ _commandRows(node) {
350
+ return node.children
351
+ .filter((child) => child.name !== this.completionCommand && !child.definition.hidden)
352
+ .map((child) => ({
353
+ label: child.definition.command || child.name,
354
+ description: child.definition.describe || '',
355
+ note: child.aliases.length ? `[aliases: ${child.aliases.join(', ')}]` : '',
356
+ }));
357
+ }
358
+
359
+ /**
360
+ * Option rows carry the alias, type and default a user needs to type the
361
+ * command. The old line dropped all three and printed long aliases with a
362
+ * single dash (`-fields`), which is not a flag.
363
+ */
364
+ _optionRows(node) {
365
+ const rows = [];
366
+ for (const spec of node.options.values()) {
367
+ const aliases = names(spec.alias).map((alias) => (alias.length === 1 ? `-${alias}` : `--${alias}`));
368
+ const type = isArrayOption(spec) ? 'array' : spec.type;
369
+ const meta = [];
370
+ if (names(spec.choices).length) meta.push(`${type || 'string'}: ${names(spec.choices).join(', ')}`);
371
+ else if (type && type !== 'boolean') meta.push(type);
372
+ if (spec.default !== undefined && spec.default !== false && spec.default !== '') meta.push(`default: ${spec.default}`);
373
+ rows.push({
374
+ label: [`--${spec.name}`, ...aliases].join(', '),
375
+ description: spec.describe || spec.description || '',
376
+ note: meta.map((part) => `[${part}]`).join(' '),
377
+ });
378
+ }
379
+ return rows;
380
+ }
381
+
334
382
  _help(node, path = []) {
335
383
  if (!path.length && this.rootHelpRenderer) {
336
384
  process.stdout.write(this.rootHelpRenderer() + "\n");
337
385
  return;
338
386
  }
339
- const lines = [node.usageText || `Usage: ${this.script} ${path.join(' ') || '<command>'}`];
340
- if (node.definition.describe) lines.push(`\n${node.definition.describe}`);
341
- const children = node.children.filter(n => n.name !== this.completionCommand && !n.definition.hidden);
342
- if (children.length) lines.push('\nCommands:\n' + children.map((n) => ` ${n.definition.command} ${n.definition.describe || ''}`).join('\n'));
343
- if (node.options.size) lines.push('\nOptions:\n' + [...node.options].map(([name, s]) => ` --${name}${s.alias ? `, -${names(s.alias).join(', -')}` : ''} ${s.describe || s.description || ''}`).join('\n'));
344
- if (node.epilogueText) lines.push(`\n${node.epilogueText}`);
345
- process.stdout.write(lines.join('\n') + '\n');
387
+ const commands = this._commandRows(node);
388
+ process.stdout.write(renderSubcommandHelp({
389
+ usage: this._usageLine(node, path, commands.length > 0),
390
+ description: node.definition.describe,
391
+ commands,
392
+ options: this._optionRows(node),
393
+ epilogue: node.epilogueText,
394
+ }));
346
395
  }
347
396
  async parse() {
348
397
  if (this.args.includes('--get-yargs-completions')) {
@@ -5,7 +5,7 @@ import { declareCapabilities } from '../capabilities.js';
5
5
  import { inspectFlow } from '../flow-inspection.js';
6
6
  import { publishFlows, publishFlowLifecycle, publishDoctor, flowStatus } from '../flow-publish.js';
7
7
  import { resolveRecord, unwrapSysId } from '../resolve-record.js';
8
- import { createFlowFromManifest, updateFlowFromManifest, readCurrentUpdateSet } from '../flow-create.js';
8
+ import { createFlowFromManifest, updateFlowFromManifest, readCurrentUpdateSet, readCatalogItemVariables } from '../flow-create.js';
9
9
  import { alignUpdateSetCapture } from '../context.js';
10
10
  import { EXCLUDED_TRIGGER_TYPES, SUPPORTED_TRIGGER_TYPES, readTriggerCatalog, readTriggerInputDefinitions } from '../flow-triggers.js';
11
11
  import { testFlow } from '../flow-test.js';
@@ -16,6 +16,8 @@ import { cancelled, pickDesignerRecord, guidedFlowCreate, guidedFlowEdit, guided
16
16
  const pickFlow = (argv, app, query = '') => pickDesignerRecord(argv, app, argv.action ? 'sys_hub_action_type_definition' : 'sys_hub_flow', argv.action ? 'action' : 'flow', query);
17
17
 
18
18
  const FLOW_COMMANDS = [
19
+ { name: 'schemas', description: 'Read live trigger catalog and input schemas' },
20
+ { name: 'catalog-variables [identifier]', description: 'List a catalog item\'s variables for a service_catalog trigger' },
19
21
  { name: 'list', description: 'List flows' },
20
22
  { name: 'executions', description: 'Show flow executions from sys_flow_context' },
21
23
  { name: 'show [identifier]', description: 'Show a flow: structure, inputs, steps and conditions' },
@@ -68,7 +70,7 @@ export function flowsCmd(wrap) {
68
70
  return yargs
69
71
  .command({
70
72
  command: 'schemas',
71
- describe: 'Read live trigger catalog and declared inputs; supported marks verified CLI creation families',
73
+ describe: 'Read live trigger catalog and input schemas',
72
74
  handler: wrap(async (_argv, app) => {
73
75
  app.requireInstance();
74
76
  const catalog = await readTriggerCatalog(app.sdk);
@@ -85,6 +87,27 @@ export function flowsCmd(wrap) {
85
87
  app.ok(data, { summary: 'Live Flow trigger schemas' });
86
88
  }),
87
89
  })
90
+ .command({
91
+ command: 'catalog-variables [identifier]',
92
+ describe: 'List a catalog item\'s variables for a service_catalog trigger input',
93
+ builder: (y) => y
94
+ .option('catalog-item', { type: 'string', describe: 'sc_cat_item sys_id used as the trigger\'s template_catalog_item' })
95
+ .option('scope', { type: 'string', describe: 'Transaction scope sys_id (default: the flow\'s own scope)' }),
96
+ handler: wrap(async (argv, app) => {
97
+ app.requireInstance();
98
+ const catalogItem = argv.catalogItem ?? argv['catalog-item'];
99
+ if (!String(catalogItem || '').trim()) throw errUsage('--catalog-item <sc_cat_item sys_id> is required; it is the trigger\'s template_catalog_item');
100
+ const identifier = await pickFlow(argv, app);
101
+ if (identifier === undefined) return;
102
+ const record = await resolveRecord(app.sdk, { table: 'sys_hub_flow', identifier, matchField: 'name', resource: 'Flow' });
103
+ const flowId = unwrapSysId(record);
104
+ const scope = argv.scope || getStringField(record, 'sys_scope') || 'global';
105
+ const result = await readCatalogItemVariables(app.sdk, app.getEffectiveInstance(), flowId, catalogItem, { scope });
106
+ app.ok(result, {
107
+ summary: `${result.count} catalog variable(s) on ${catalogItem}; trigger catalog_variables input: ${result.catalog_variables_input || '(none)'}`,
108
+ });
109
+ }),
110
+ })
88
111
  .command({
89
112
  command: 'list',
90
113
  aliases: ['ls'],
@@ -316,11 +339,13 @@ export function flowsCmd(wrap) {
316
339
  })
317
340
  .command({
318
341
  command: 'create',
319
- describe: 'Create a draft flow from a JSON manifest or guided prompts. Use `jsn flows schemas` for instance-derived trigger and input schemas, and `jsn actions action-type-schema --id <actionTypeId> --scope <scopeId>` for provider action inputs. Manifest structure remains code-owned.',
342
+ describe: 'Create a draft flow from a JSON manifest or guided prompts',
320
343
  builder: (y) => y
321
344
  .option('data', { type: 'string', describe: 'Flow manifest as inline JSON' })
322
345
  .option('data-file', { type: 'string', describe: 'Read the flow manifest from a JSON file' })
323
- .option('scope', { type: 'string', describe: 'Transaction scope sys_id or global for the guided picker' }),
346
+ .option('scope', { type: 'string', describe: 'Transaction scope sys_id or global for the guided picker' })
347
+ .epilogue('Manifest structure is code-owned. Use `jsn flows schemas` for trigger and input schemas, and\n'
348
+ + '`jsn actions action-type-schema --id <actionTypeId> --scope <scopeId>` for provider action inputs.'),
324
349
  handler: wrap(async (argv, app) => {
325
350
  app.requireInstance();
326
351
  const dataFile = argv.dataFile ?? argv['data-file'];
@@ -345,12 +370,21 @@ export function flowsCmd(wrap) {
345
370
  .command({
346
371
  command: 'update [identifier]',
347
372
  aliases: ['edit'],
348
- describe: 'Save partial edits to a Draft, or to a published/active flow whose ProcessFlow definition reports security.can_write=true: record_create_or_update trigger table/condition and existing action inputs. Published flows are edited as their working definition; the published snapshot and runtime pointers must stay unchanged, and the command fails loudly if they do not. Flows without write access are refused before any lock or content write, naming the permission. Use --preview for before/after values without writes. Flow Logic, variables, catalog-trigger edits and stage placement require Flow Designer. Never publishes or executes. Use `jsn flows schemas` and `jsn actions action-type-schema --id <actionTypeId> --scope <scopeId>` for live schemas; omitted values are preserved.',
373
+ describe: 'Update a draft, or a published flow that reports write access',
349
374
  builder: (y) => y
350
375
  .option('data', { type: 'string', describe: 'Update manifest as inline JSON' })
351
376
  .option('data-file', { type: 'string', describe: 'Read the update manifest from a JSON file' })
352
377
  .option('preview', { type: 'boolean', default: false, describe: 'Validate and show exact before/after input values without saving or versioning' })
353
- .option('force', { type: 'boolean', default: false, describe: 'Skip confirmation' }),
378
+ .option('force', { type: 'boolean', default: false, describe: 'Skip confirmation' })
379
+ .epilogue('Editable: record_create_or_update trigger table/condition, existing action inputs, and stage\n'
380
+ + 'placement (add a stage, or move flow steps onto one with componentIndexes). A service_catalog\n'
381
+ + 'trigger is created with its template_catalog_item and catalog_variables inputs. A published flow\n'
382
+ + 'is edited as its working definition; the published snapshot and runtime pointers must stay\n'
383
+ + 'unchanged, and the command fails loudly if they do not. A flow without write access is refused\n'
384
+ + 'before any lock or content write, naming the permission. Flow Logic, flow variables, subflows and\n'
385
+ + 'error handling still need Flow Designer. Never publishes or executes; omitted values are preserved.\n'
386
+ + 'Live schemas: `jsn flows schemas` and `jsn actions action-type-schema --id <actionTypeId>\n'
387
+ + '--scope <scopeId>`.'),
354
388
  handler: wrap(async (argv, app) => {
355
389
  app.requireInstance();
356
390
  const dataFile = argv.dataFile ?? argv['data-file'];
@@ -387,9 +421,13 @@ export function flowsCmd(wrap) {
387
421
  })
388
422
  .command({
389
423
  command: 'unlock [identifier]',
390
- describe: 'Release this user\'s stale Flow Designer safe-edit session on a flow. Recovery for an orphaned lease left by a failed update: the provider only releases the calling user\'s own session, the before/after canUserEdit and currentEditor values are printed, and an unconfirmed release fails instead of reporting success. Does not edit content, publish, or touch another user\'s session.',
424
+ describe: 'Release this user\'s stale safe-edit lease after a failed update',
391
425
  builder: (y) => y
392
- .option('force', { type: 'boolean', default: false, describe: 'Skip confirmation' }),
426
+ .option('force', { type: 'boolean', default: false, describe: 'Skip confirmation' })
427
+ .epilogue('Recovery for an orphaned lease left by a failed update: the provider only releases the calling\n'
428
+ + 'user\'s own session, the before/after canUserEdit and currentEditor values are printed, and an\n'
429
+ + 'unconfirmed release fails instead of reporting success. Does not edit content, publish, or touch\n'
430
+ + 'another user\'s session.'),
393
431
  handler: wrap(async (argv, app) => {
394
432
  app.requireInstance();
395
433
  const identifier = await pickFlow(argv, app);
@@ -412,14 +450,16 @@ export function flowsCmd(wrap) {
412
450
  })
413
451
  .command({
414
452
  command: 'delete [identifier]',
415
- describe: 'Delete a flow (not yet implemented)',
453
+ describe: 'Delete a flow (not implemented: use the Flow Designer UI)',
416
454
  handler: wrap(async (argv, app) => {
417
455
  const identifier = await pickFlow(argv, app);
418
456
  if (identifier === undefined) return;
419
457
  throw errUsage('Flow deletion requires the Flow Designer GraphQL API - not yet implemented.\n'
420
458
  + 'Use the ServiceNow web UI to delete flows.');
421
459
  }),
422
- });
460
+ })
461
+ .epilogue('Run "jsn flows <command> --help" for details. In a terminal you can omit the target and pick\n'
462
+ + 'one; scripts use explicit identifiers and manifests.');
423
463
  },
424
464
  handler: wrap(async (_argv, app) => {
425
465
  const summary = 'Manage Flow Designer flows from the sys_hub_flow table. Flow structure comes from the ProcessFlow API, so V1, V2 and subflow definitions all render in full.';
@@ -159,6 +159,7 @@ export function validateFlowManifest(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
161
  if (manifest.errorHandling !== undefined) throw new Error('Error handling is unsupported in this creation slice');
162
+ if (manifest.stages !== undefined) validateStages(manifest.stages);
162
163
  const trigger = manifest.trigger;
163
164
  if (!trigger || typeof trigger !== 'object' || Array.isArray(trigger)) throw new Error('Flow manifest requires a trigger object');
164
165
  for (const key of Object.keys(trigger)) if (!['type', 'table', 'condition', 'inputs'].includes(key)) throw new Error(`Flow manifest trigger field "${key}" is unsupported`);
@@ -195,6 +196,139 @@ export function buildFlowProperties(manifest) {
195
196
  };
196
197
  }
197
198
 
199
+ // Stage placement. Shapes come from a captured Flow Designer session that both
200
+ // created stages and moved steps onto them: the V1-style
201
+ // `PUT /processflow/flow/{id}/stages` body and the `stages {insert|update}`
202
+ // snFlowDesigner patch. A stage carries a UUID `stageId`, a display `label`, a
203
+ // machine `value`, an `order`, and `componentIndexes` — the flow-step orders
204
+ // placed on that stage. `componentIndexes` is why a placement update must run
205
+ // after the actions exist.
206
+ const STAGE_DURATION = '1970-01-01 00:00:00';
207
+ const STAGE_STATES = Object.freeze({
208
+ pending: 'Pending - has not started',
209
+ in_progress: 'In progress',
210
+ skipped: 'Skipped',
211
+ complete: 'Completed',
212
+ error: 'Error',
213
+ });
214
+ const STAGE_KEYS = ['label', 'value', 'order', 'system', 'componentIndexes', 'stageId', 'duration', 'states'];
215
+
216
+ const asBool = (value) => value === true || value === 'true';
217
+
218
+ function stageValueFromLabel(label) {
219
+ return String(label).trim().toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '');
220
+ }
221
+
222
+ /**
223
+ * Validate a manifest `stages` array.
224
+ *
225
+ * `stageId` is only meaningful for updates: an entry without one inserts a new
226
+ * stage, an entry with one edits the stage it names.
227
+ */
228
+ export function validateStages(stages, { update = false } = {}) {
229
+ if (!Array.isArray(stages)) throw new Error('Flow stages must be an array');
230
+ for (const [index, stage] of stages.entries()) {
231
+ const where = `Stage ${index + 1}`;
232
+ if (!stage || typeof stage !== 'object' || Array.isArray(stage)) throw new Error(`${where} must be an object`);
233
+ for (const key of Object.keys(stage)) if (!STAGE_KEYS.includes(key)) throw new Error(`${where} field "${key}" is unsupported`);
234
+ if (stage.stageId !== undefined && !update) throw new Error(`${where} stageId is only accepted when updating an existing stage; omit it to insert`);
235
+ if (update && stage.stageId !== undefined && !/^[0-9a-fA-F-]{32,36}$/.test(String(stage.stageId))) throw new Error(`${where} stageId must be the stage UUID`);
236
+ if (stage.label !== undefined && !String(stage.label).trim()) throw new Error(`${where} label must not be empty`);
237
+ if (stage.value !== undefined && !String(stage.value).trim()) throw new Error(`${where} value must not be empty`);
238
+ if (stage.order !== undefined && (!Number.isInteger(stage.order) || stage.order < 0)) throw new Error(`${where} order must be a non-negative integer`);
239
+ if (stage.system !== undefined && typeof stage.system !== 'boolean') throw new Error(`${where} system must be a boolean`);
240
+ if (stage.componentIndexes !== undefined) {
241
+ if (!Array.isArray(stage.componentIndexes) || stage.componentIndexes.some(value => !Number.isInteger(value) || value < 1)) {
242
+ throw new Error(`${where} componentIndexes must be an array of flow-step orders (integers >= 1)`);
243
+ }
244
+ }
245
+ if (stage.duration !== undefined && typeof stage.duration !== 'string') throw new Error(`${where} duration must be a string`);
246
+ if (stage.states !== undefined && (!stage.states || typeof stage.states !== 'object' || Array.isArray(stage.states))) throw new Error(`${where} states must be an object`);
247
+ const inserts = stage.stageId === undefined;
248
+ if (inserts && !String(stage.label ?? '').trim()) throw new Error(`${where} requires a label`);
249
+ if (!inserts) {
250
+ const edited = ['label', 'value', 'order', 'componentIndexes'].filter(key => stage[key] !== undefined);
251
+ if (!edited.length) throw new Error(`${where} must change label, value, order or componentIndexes`);
252
+ }
253
+ }
254
+ return stages;
255
+ }
256
+
257
+ export function buildStageInserts(stages = [], idFactory = () => randomUUID()) {
258
+ return stages
259
+ .map((stage, index) => ({ stage, index }))
260
+ .sort((a, b) => (a.stage.order ?? a.index) - (b.stage.order ?? b.index))
261
+ .map(({ stage, index }) => ({
262
+ stageId: idFactory(),
263
+ label: String(stage.label).trim(),
264
+ value: stage.value ?? stageValueFromLabel(stage.label),
265
+ order: stage.order ?? index,
266
+ system: stage.system ?? false,
267
+ componentIndexes: stage.componentIndexes ?? [],
268
+ duration: stage.duration ?? STAGE_DURATION,
269
+ states: stage.states ?? STAGE_STATES,
270
+ }));
271
+ }
272
+
273
+ export function buildStageUpdates(stages = []) {
274
+ return stages.map((stage) => {
275
+ const update = { stageId: stage.stageId };
276
+ if (stage.label !== undefined) update.label = String(stage.label).trim();
277
+ if (stage.value !== undefined) update.value = stage.value;
278
+ if (stage.order !== undefined) update.order = stage.order;
279
+ if (stage.componentIndexes !== undefined) update.componentIndexes = stage.componentIndexes;
280
+ return update;
281
+ });
282
+ }
283
+
284
+ /**
285
+ * `stages` is part of the same snFlowDesigner patch as actions, but placement
286
+ * has to follow the actions: `componentIndexes` name flow-step orders that must
287
+ * already exist. Creation therefore sends stages in a second patch.
288
+ */
289
+ export function buildFlowStageMutation({ flowId, inserts = [], updates = [] }) {
290
+ const parts = [];
291
+ if (inserts.length) parts.push(`insert: [${inserts.map(gqlInputObject).join(', ')}]`);
292
+ if (updates.length) parts.push(`update: [${updates.map(gqlInputObject).join(', ')}]`);
293
+ if (!parts.length) throw new Error('Flow stage patch requires at least one insert or update');
294
+ return `mutation { global { snFlowDesigner { flow(flowPatch: {flowId: ${gqlString(flowId)}, stages: {${parts.join(', ')}}}) { id stages { inserts { sysId } } } } } }`;
295
+ }
296
+
297
+ /**
298
+ * Read the catalog item's variables as a `service_catalog` flow sees them.
299
+ *
300
+ * A service_catalog trigger takes `template_catalog_item` (an sc_cat_item
301
+ * sys_id) plus `catalog_variables`, a comma-joined list of item_option_new
302
+ * sys_ids. This is the lookup Flow Designer runs when you pick the item, so the
303
+ * ids a manifest needs are the `id` values returned here.
304
+ */
305
+ export async function readCatalogItemVariables(sdk, instance, flowId, catalogItemId, { scope = 'global', includeMultiRowVariableSets = true, selectedVariables = '' } = {}) {
306
+ if (!String(catalogItemId || '').trim()) throw new Error('catalog-variables requires a catalog item sys_id');
307
+ const query = new URLSearchParams({ sysparm_transaction_scope: scope });
308
+ const response = await sdk.request(`${instance}${FLOW_ENDPOINT}/${encodeURIComponent(flowId)}/service_get_catalog_variables?${query}`, {
309
+ method: 'POST',
310
+ body: JSON.stringify({ flow_catalog_model: catalogItemId, includeMultiRowVariableSets, selectedVariables }),
311
+ });
312
+ const data = response?.result?.data;
313
+ if (!data || !Array.isArray(data.availableList)) throw new Error('Catalog variable lookup returned no availableList; check the flow and catalog item sys_ids and the transaction scope');
314
+ const variables = data.availableList.map(variable => ({
315
+ id: stringValue(variable.id),
316
+ name: stringValue(variable.name),
317
+ label: stringValue(variable.label),
318
+ type: stringValue(variable.type),
319
+ mandatory: asBool(variable.mandatory),
320
+ readonly: asBool(variable.readonly),
321
+ }));
322
+ return {
323
+ flow_id: flowId,
324
+ catalog_item: catalogItemId,
325
+ count: variables.length,
326
+ variables,
327
+ // Exactly what the trigger input expects, so it can be pasted into a manifest.
328
+ catalog_variables_input: variables.map(variable => variable.id).join(','),
329
+ };
330
+ }
331
+
198
332
  export function buildFlowPatchMutation({ flowId, trigger, actions }) {
199
333
  const triggerInsert = {
200
334
  flowSysId: trigger.flowSysId,
@@ -223,12 +357,17 @@ export function buildFlowPatchMutation({ flowId, trigger, actions }) {
223
357
  return `mutation { global { snFlowDesigner { flow(${patch}) { triggerInstances { inserts { sysId } updates } actions { inserts { sysId uiUniqueIdentifier } } } } } }`;
224
358
  }
225
359
 
226
- export function buildFlowUpdateMutation({ flowId, triggerUpdates = [], actionUpdates = [] }) {
360
+ export function buildFlowUpdateMutation({ flowId, triggerUpdates = [], actionUpdates = [], stageInserts = [], stageUpdates = [] }) {
227
361
  const updates = [];
228
362
  if (triggerUpdates.length) updates.push(`triggerInstances: {update: [${triggerUpdates.map(gqlInputObject).join(', ')}]}`);
229
363
  if (actionUpdates.length) updates.push(`actions: {update: [${actionUpdates.map(gqlInputObject).join(', ')}]}`);
364
+ const stageParts = [];
365
+ if (stageInserts.length) stageParts.push(`insert: [${stageInserts.map(gqlInputObject).join(', ')}]`);
366
+ if (stageUpdates.length) stageParts.push(`update: [${stageUpdates.map(gqlInputObject).join(', ')}]`);
367
+ if (stageParts.length) updates.push(`stages: {${stageParts.join(', ')}}`);
368
+ if (!updates.length) throw new Error('Flow update mutation requires at least one change');
230
369
  const patch = `flowPatch: {flowId: ${gqlString(flowId)}, ${updates.join(', ')}}`;
231
- return `mutation { global { snFlowDesigner { flow(${patch}) { triggerInstances { updates } actions { updates } } } } }`;
370
+ return `mutation { global { snFlowDesigner { flow(${patch}) { triggerInstances { updates } actions { updates } stages { inserts { sysId } } } } } }`;
232
371
  }
233
372
 
234
373
  export async function readProcessFlow(sdk, instance, flowId, scope) {
@@ -384,6 +523,31 @@ function actionTypeIdOf(action) {
384
523
  return idValue(action?.actionTypeSysId || action?.action_type_sys_id || action?.actionType?.sys_id || action?.actionType?.sysId);
385
524
  }
386
525
 
526
+ /**
527
+ * Confirm the stages this command asked for are the ones the flow now carries.
528
+ * Matching is by generated stageId: a label-only check could pass while the
529
+ * placement landed on a different stage.
530
+ */
531
+ function assertStagesPlaced(processflow, stageInserts, flowId) {
532
+ if (!stageInserts.length) return;
533
+ const saved = findArray(processflow, 'stages');
534
+ if (!saved.length) throw new Error(`Flow ${flowId} stage read-back returned no stages after placing ${stageInserts.length}`);
535
+ for (const expected of stageInserts) {
536
+ const matches = saved.filter(stage => stringValue(stage.stageId || stage.stage_id) === expected.stageId);
537
+ if (matches.length !== 1) throw new Error(`Flow ${flowId} stage "${expected.label}" (${expected.stageId}) was not uniquely present in ProcessFlow read-back`);
538
+ const savedStage = matches[0];
539
+ if (expected.label !== undefined && stringValue(savedStage.label) !== expected.label) throw new Error(`Flow ${flowId} stage ${expected.stageId} label did not match the requested "${expected.label}"`);
540
+ if (expected.order !== undefined && String(savedStage.order) !== String(expected.order)) throw new Error(`Flow ${flowId} stage ${expected.stageId} order did not match the requested ${expected.order}`);
541
+ if (expected.componentIndexes !== undefined) {
542
+ const savedIndexes = (Array.isArray(savedStage.componentIndexes) ? savedStage.componentIndexes : []).map(String).sort();
543
+ const expectedIndexes = expected.componentIndexes.map(String).sort();
544
+ if (JSON.stringify(savedIndexes) !== JSON.stringify(expectedIndexes)) {
545
+ throw new Error(`Flow ${flowId} stage ${expected.stageId} placement did not match the requested componentIndexes`);
546
+ }
547
+ }
548
+ }
549
+ }
550
+
387
551
  function verifyCreatedFlowReadback({ flowId, processflow, trigger, insertedTrigger, manifest, actionInstances, inserted }) {
388
552
  const returnedFlowId = stringValue(processflow.flowId || processflow.flow_id || processflow.sysId || processflow.sys_id);
389
553
  if (returnedFlowId && returnedFlowId !== flowId) throw new Error(`ProcessFlow read-back returned a different flow ID (${returnedFlowId})`);
@@ -549,8 +713,8 @@ async function resolveExistingAction(sdk, actions, requested, index) {
549
713
 
550
714
  export function validateFlowUpdateManifest(manifest) {
551
715
  if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) throw new Error('Flow update manifest must be a JSON object');
552
- const allowed = new Set(['scope', 'trigger', 'actions']);
553
- for (const key of Object.keys(manifest)) if (!allowed.has(key)) throw new Error(`Flow update field "${key}" is unsupported; only trigger and existing action inputs may be updated`);
716
+ const allowed = new Set(['scope', 'trigger', 'actions', 'stages']);
717
+ 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`);
554
718
  if (manifest.scope !== undefined && !String(manifest.scope).trim()) throw new Error('Flow update scope must not be empty');
555
719
  if (manifest.trigger !== undefined) {
556
720
  if (!manifest.trigger || typeof manifest.trigger !== 'object' || Array.isArray(manifest.trigger)) throw new Error('Flow update trigger must be an object');
@@ -571,7 +735,8 @@ export function validateFlowUpdateManifest(manifest) {
571
735
  if (Object.keys(action.inputs).length === 0) throw new Error(`Update action ${index + 1} inputs must contain at least one changed value`);
572
736
  }
573
737
  }
574
- if (manifest.trigger === undefined && manifest.actions === undefined) throw new Error('Flow update manifest must specify trigger and/or actions');
738
+ if (manifest.trigger === undefined && manifest.actions === undefined && manifest.stages === undefined) throw new Error('Flow update manifest must specify trigger, actions and/or stages');
739
+ if (manifest.stages !== undefined) validateStages(manifest.stages, { update: true });
575
740
  return manifest;
576
741
  }
577
742
 
@@ -949,8 +1114,20 @@ export async function createFlowFromManifest(sdk, instance, inputManifest, optio
949
1114
  const inserted = insertedActions(patchResponse);
950
1115
  if (inserted.length !== actionInstances.length) throw new Error(`Flow action patch returned ${inserted.length} inserted action identities; expected ${actionInstances.length}`);
951
1116
 
1117
+ // Stages carry componentIndexes that name flow-step orders, so placement
1118
+ // runs after the actions exist — the same order Flow Designer uses.
1119
+ const stageInserts = buildStageInserts(manifest.stages || [], idFactory);
1120
+ if (stageInserts.length) {
1121
+ const stageResponse = await mutationContext('stage_placement', readUpdateSet, snapshots, () => sdk.request(`${instance}${GRAPHQL_ENDPOINT}`, {
1122
+ method: 'POST',
1123
+ body: JSON.stringify({ query: buildFlowStageMutation({ flowId, inserts: stageInserts }), variables: {} }),
1124
+ }), updateSet => readUpdateSetCapture(sdk, updateSet, flowId));
1125
+ assertGraphQLSuccess(stageResponse, 'Flow stage placement');
1126
+ }
1127
+
952
1128
  const processflow = await readProcessFlow(sdk, instance, flowId, scope);
953
- verifyCreatedFlowReadback({ flowId, processflow, trigger, insertedTrigger, manifest, actionInstances, inserted });
1129
+ verifyCreatedFlowReadback({ flowId, processflow, trigger, insertedTrigger, manifest, actionInstances, inserted, stageInserts });
1130
+ assertStagesPlaced(processflow, stageInserts, flowId);
954
1131
  const { version } = await mutationContext('autosave_version', readUpdateSet, snapshots, () => createVerifiedFlowVersion(sdk, {
955
1132
  instance, flowId, scope, type: 'Autosave', annotation: 'JSN flow create',
956
1133
  }), updateSet => readUpdateSetCapture(sdk, updateSet, flowId));
@@ -1013,6 +1190,8 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1013
1190
  const snapshots = [];
1014
1191
  const triggerUpdates = [];
1015
1192
  const actionUpdates = [];
1193
+ const stageInserts = buildStageInserts((manifest.stages || []).filter(stage => stage.stageId === undefined), options.idFactory || (() => randomUUID()));
1194
+ const stageUpdates = buildStageUpdates((manifest.stages || []).filter(stage => stage.stageId !== undefined));
1016
1195
  const changedActionInputs = new Map();
1017
1196
  const actionTargets = new Map();
1018
1197
  const changes = [];
@@ -1040,7 +1219,20 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1040
1219
  changedActionInputs.set(uiId, new Set(Object.keys(requested.inputs)));
1041
1220
  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 });
1042
1221
  }
1043
- if (triggerUpdates.length === 0 && actionUpdates.length === 0) throw new Error(`Flow ${flowId} update has no supported changes`);
1222
+ const savedStages = findArray(beforeDefinition, 'stages');
1223
+ const savedStageById = new Map(savedStages.map(stage => [stringValue(stage.stageId || stage.stage_id), stage]));
1224
+ for (const update of stageUpdates) {
1225
+ const before = savedStageById.get(update.stageId);
1226
+ if (!before) throw new Error(`Flow ${flowId} has no stage ${update.stageId}; omit stageId to insert a new stage`);
1227
+ for (const [field, after] of Object.entries(update)) {
1228
+ if (field === 'stageId') continue;
1229
+ changes.push({ component: 'stage', stage: stringValue(before.label), input: field, before: before[field], after });
1230
+ }
1231
+ }
1232
+ for (const insert of stageInserts) {
1233
+ changes.push({ component: 'stage', stage: insert.label, input: 'insert', before: null, after: { order: insert.order, componentIndexes: insert.componentIndexes } });
1234
+ }
1235
+ if (triggerUpdates.length === 0 && actionUpdates.length === 0 && stageInserts.length === 0 && stageUpdates.length === 0) throw new Error(`Flow ${flowId} update has no supported changes`);
1044
1236
  if (options.preview) return {
1045
1237
  preview: true,
1046
1238
  flow: { id: flowId, name: target.flowName, status: lifecycle.status, active: lifecycle.active },
@@ -1069,15 +1261,31 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1069
1261
  try {
1070
1262
  const patchResponse = await mutationContext('trigger_and_actions_update', readUpdateSet, snapshots, () => sdk.request(`${instance}${GRAPHQL_ENDPOINT}`, {
1071
1263
  method: 'POST',
1072
- body: JSON.stringify({ query: buildFlowUpdateMutation({ flowId, triggerUpdates, actionUpdates }), variables: {} }),
1264
+ body: JSON.stringify({ query: buildFlowUpdateMutation({ flowId, triggerUpdates, actionUpdates, stageInserts, stageUpdates }), variables: {} }),
1073
1265
  }), updateSet => readUpdateSetCapture(sdk, updateSet, flowId));
1074
1266
  assertGraphQLSuccess(patchResponse, 'Flow trigger/action update');
1075
1267
  completedStage = 'patch_acknowledged';
1076
1268
  const processflow = await readProcessFlow(sdk, instance, flowId, scope);
1077
1269
  // Only requested values may differ. Preserve array order and opaque fields.
1078
- for (const field of ['flowVariables', 'flowLogicInstances', 'subFlowInstances', 'flowInputs', 'flowOutputs', 'inputs', 'outputs', 'stages']) {
1270
+ // `stages` is compared separately below: a stage edit may touch specific
1271
+ // fields, while every stage the manifest did not name must stay identical.
1272
+ for (const field of ['flowVariables', 'flowLogicInstances', 'subFlowInstances', 'flowInputs', 'flowOutputs', 'inputs', 'outputs']) {
1079
1273
  if (!isDeepStrictEqual(beforeDefinition[field], processflow[field])) throw new Error(`Flow ${flowId} changed omitted ${field}; preservation failed`);
1080
1274
  }
1275
+ if (stageInserts.length || stageUpdates.length) {
1276
+ const requestedStageIds = new Set([...stageInserts.map(stage => stage.stageId), ...stageUpdates.map(stage => stage.stageId)]);
1277
+ const untouched = definition => findArray(definition, 'stages')
1278
+ .filter(stage => !requestedStageIds.has(stringValue(stage.stageId || stage.stage_id)));
1279
+ if (!isDeepStrictEqual(untouched(beforeDefinition), untouched(processflow))) throw new Error(`Flow ${flowId} changed omitted stages; preservation failed`);
1280
+ assertStagesPlaced(processflow, [...stageInserts, ...stageUpdates.map(update => ({
1281
+ stageId: update.stageId,
1282
+ label: update.label ?? stringValue(savedStageById.get(update.stageId)?.label),
1283
+ order: update.order ?? savedStageById.get(update.stageId)?.order,
1284
+ componentIndexes: update.componentIndexes,
1285
+ }))].filter(stage => stage.label !== undefined), flowId);
1286
+ } else if (!isDeepStrictEqual(beforeDefinition.stages, processflow.stages)) {
1287
+ throw new Error(`Flow ${flowId} changed omitted stages; preservation failed`);
1288
+ }
1081
1289
  if (!triggerUpdate && !isDeepStrictEqual(beforeDefinition.triggerInstances, processflow.triggerInstances)) throw new Error(`Flow ${flowId} changed omitted triggerInstances`);
1082
1290
  const maskActions = definition => findExistingActions(definition).map(action => {
1083
1291
  const copy = clone(action);
package/src/help.js CHANGED
@@ -258,3 +258,99 @@ export function renderHelp(config, registry = null) {
258
258
  '',
259
259
  ].join('\n');
260
260
  }
261
+
262
+ // Subcommand pages (`jsn flows --help`) used to print one unbroken line per
263
+ // entry. A description written for a command's own page — `flows update` is
264
+ // ~700 characters — became an 801-column line that the terminal cut off, so the
265
+ // list advertised a command nobody could read and options lost their aliases,
266
+ // types and defaults. These helpers wrap the text to the terminal instead.
267
+
268
+ const HELP_WIDTH_FALLBACK = 100;
269
+
270
+ /**
271
+ * Columns available to help text. A piped run has no `columns`, and a very wide
272
+ * terminal should not stretch prose to 200 columns, so cap it.
273
+ */
274
+ export function helpWidth(stream = process.stdout) {
275
+ const columns = Number(stream?.columns);
276
+ if (!Number.isFinite(columns) || columns <= 0) return HELP_WIDTH_FALLBACK;
277
+ return Math.min(columns, HELP_WIDTH_FALLBACK);
278
+ }
279
+
280
+ /**
281
+ * Wrap `text` into lines no wider than `width`, indenting `firstIndent` spaces
282
+ * on the first line and `indent` on the rest. A word longer than the available
283
+ * width stays whole: a split alias or sys_id reads as a different token.
284
+ */
285
+ export function wrapText(text, { width, firstIndent = 0, indent = firstIndent } = {}) {
286
+ const words = String(text ?? '').split(/\s+/).filter(Boolean);
287
+ if (!words.length) return [];
288
+ const limit = Number.isFinite(width) && width > 0 ? width : HELP_WIDTH_FALLBACK;
289
+ const lines = [];
290
+ let line = '';
291
+ let prefix = ' '.repeat(firstIndent);
292
+ for (const word of words) {
293
+ const candidate = line ? `${line} ${word}` : word;
294
+ if (line && prefix.length + candidate.length > limit) {
295
+ lines.push(prefix + line);
296
+ line = word;
297
+ prefix = ' '.repeat(indent);
298
+ } else {
299
+ line = candidate;
300
+ }
301
+ }
302
+ lines.push(prefix + line);
303
+ return lines;
304
+ }
305
+
306
+ /**
307
+ * Render help rows as one padded label column plus a wrapped description.
308
+ *
309
+ * @param {Array<{label: string, description?: string, note?: string}>} rows
310
+ * `note` is appended verbatim (already bracketed) — aliases, option type and
311
+ * default — so the description itself stays plain prose.
312
+ * @param {{width?: number, indent?: number}} [opts]
313
+ */
314
+ export function renderRows(rows, { width = helpWidth(), indent = 2 } = {}) {
315
+ if (!rows.length) return '';
316
+ const labelWidth = Math.max(...rows.map(row => row.label.length));
317
+ const descriptionIndent = indent + labelWidth + 2;
318
+ const available = Math.max(20, width - descriptionIndent);
319
+ const lines = [];
320
+ for (const row of rows) {
321
+ const head = `${' '.repeat(indent)}${row.label.padEnd(labelWidth)}`.padEnd(descriptionIndent);
322
+ const wrapped = wrapText(row.description, { width: available });
323
+ // The note (aliases, type, default) is one token: splitting `[aliases: runs,
324
+ // contexts]` across lines leaves a bracket fragment that reads as prose.
325
+ if (row.note) {
326
+ const last = wrapped.at(-1);
327
+ if (last !== undefined && last.length + 1 + row.note.length <= available) wrapped[wrapped.length - 1] = `${last} ${row.note}`;
328
+ else wrapped.push(row.note);
329
+ }
330
+ if (!wrapped.length) {
331
+ lines.push(head.trimEnd());
332
+ continue;
333
+ }
334
+ lines.push(`${head}${wrapped[0]}`);
335
+ for (const line of wrapped.slice(1)) lines.push(`${' '.repeat(descriptionIndent)}${line}`);
336
+ }
337
+ return lines.join('\n');
338
+ }
339
+
340
+ /**
341
+ * Render one command page: usage, description, subcommands, options, epilogue.
342
+ * Sections are separated by a blank line so the list is skimmable in a
343
+ * terminal; nothing is emitted for an empty section. The epilogue is authored
344
+ * text and prints verbatim: it is where command examples live, and breaking
345
+ * `jsn records watch --table incident` at a flag boundary turns one
346
+ * copy-pasteable command into two wrong ones.
347
+ */
348
+ export function renderSubcommandHelp({ usage, description, commands = [], options = [], epilogue, width = helpWidth() }) {
349
+ const blocks = [usage];
350
+ if (description) blocks.push(description);
351
+ if (commands.length) blocks.push(`Commands:\n${renderRows(commands, { width })}`);
352
+ if (options.length) blocks.push(`Options:\n${renderRows(options, { width })}`);
353
+ if (epilogue) blocks.push(epilogue);
354
+ return `${blocks.join('\n\n')}\n`;
355
+ }
356
+
@@ -53,8 +53,8 @@ export default {
53
53
  options: { singular: 'UI macro', scopeValidation: true } },
54
54
  uxlists: { table: 'sys_ux_list', aliases: ['uxlist'], columns: ['name', 'active', 'sys_scope'],
55
55
  options: { singular: 'workspace list', scopeValidation: true, readOnly: true } },
56
- uxapplicability: { table: 'sys_ux_applicability_m2m', aliases: ['uxapp'], columns: ['name', 'active', 'sys_scope'],
57
- options: { singular: 'workspace applicability', scopeValidation: true, readOnly: true } },
56
+ uxapplicability: { table: 'sys_ux_applicability_m2m_list', aliases: ['uxapp'], columns: ['list', 'applicability', 'active', 'order', 'sys_scope'],
57
+ identifierField: 'sys_id', options: { singular: 'workspace applicability', scopeValidation: true, readOnly: true } },
58
58
  cataloguipolicies: { table: 'catalog_ui_policy', aliases: ['cataloguipolicy', 'cup'], columns: ['short_description', 'catalog_item', 'variable_set', 'active', 'sys_scope'],
59
59
  options: { singular: 'catalog UI policy', scopeValidation: true } },
60
60
  tables: { table: 'sys_db_object', aliases: ['table', 't'], columns: ['name', 'label', 'super_class', 'create_access_controls'],