@jacebenson/jsn 5.4.0 → 5.5.0-dev.155.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.
@@ -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,161 @@ 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
+ // ProcessFlow returns `states` as a list of {label, name}; the REST stage map
208
+ // (PUT /processflow/flow/{id}/stages) returns it keyed by name. Sending the
209
+ // keyed form is not what Flow Designer sends, so use the list on insert.
210
+ const STAGE_STATES = [
211
+ { label: 'Pending - has not started', name: 'pending' },
212
+ { label: 'In progress', name: 'in_progress' },
213
+ { label: 'Skipped', name: 'skipped' },
214
+ { label: 'Completed', name: 'complete' },
215
+ { label: 'Error', name: 'error' },
216
+ ];
217
+ const STAGE_KEYS = ['label', 'value', 'order', 'system', 'componentIndexes', 'stageId', 'duration', 'states'];
218
+
219
+ const asBool = (value) => value === true || value === 'true';
220
+
221
+ /**
222
+ * Stages as a list, whichever shape the definition uses.
223
+ *
224
+ * ProcessFlow readback carries `stages` as an object keyed by stageId; the REST
225
+ * stage map uses the same shape while a definition built in code may hold an
226
+ * array. Treating only the array form as data made a live flow look like it had
227
+ * no stages at all.
228
+ */
229
+ export function stageList(definition) {
230
+ const stages = definition?.stages;
231
+ if (Array.isArray(stages)) return stages;
232
+ if (stages && typeof stages === 'object') return Object.values(stages).filter(stage => stage && typeof stage === 'object');
233
+ return [];
234
+ }
235
+
236
+ function stageValueFromLabel(label) {
237
+ return String(label).trim().toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '');
238
+ }
239
+
240
+ /**
241
+ * Validate a manifest `stages` array.
242
+ *
243
+ * `stageId` is only meaningful for updates: an entry without one inserts a new
244
+ * stage, an entry with one edits the stage it names.
245
+ */
246
+ export function validateStages(stages, { update = false } = {}) {
247
+ if (!Array.isArray(stages)) throw new Error('Flow stages must be an array');
248
+ for (const [index, stage] of stages.entries()) {
249
+ const where = `Stage ${index + 1}`;
250
+ if (!stage || typeof stage !== 'object' || Array.isArray(stage)) throw new Error(`${where} must be an object`);
251
+ for (const key of Object.keys(stage)) if (!STAGE_KEYS.includes(key)) throw new Error(`${where} field "${key}" is unsupported`);
252
+ if (stage.stageId !== undefined && !update) throw new Error(`${where} stageId is only accepted when updating an existing stage; omit it to insert`);
253
+ 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`);
254
+ if (stage.label !== undefined && !String(stage.label).trim()) throw new Error(`${where} label must not be empty`);
255
+ if (stage.value !== undefined && !String(stage.value).trim()) throw new Error(`${where} value must not be empty`);
256
+ if (stage.order !== undefined && (!Number.isInteger(stage.order) || stage.order < 0)) throw new Error(`${where} order must be a non-negative integer`);
257
+ if (stage.system !== undefined && typeof stage.system !== 'boolean') throw new Error(`${where} system must be a boolean`);
258
+ if (stage.componentIndexes !== undefined) {
259
+ if (!Array.isArray(stage.componentIndexes) || stage.componentIndexes.some(value => !Number.isInteger(value) || value < 1)) {
260
+ throw new Error(`${where} componentIndexes must be an array of flow-step orders (integers >= 1)`);
261
+ }
262
+ }
263
+ if (stage.duration !== undefined && typeof stage.duration !== 'string') throw new Error(`${where} duration must be a string`);
264
+ if (stage.states !== undefined && (!stage.states || typeof stage.states !== 'object' || Array.isArray(stage.states))) throw new Error(`${where} states must be an object`);
265
+ const inserts = stage.stageId === undefined;
266
+ if (inserts && !String(stage.label ?? '').trim()) throw new Error(`${where} requires a label`);
267
+ if (!inserts) {
268
+ const edited = ['label', 'value', 'order', 'componentIndexes'].filter(key => stage[key] !== undefined);
269
+ if (!edited.length) throw new Error(`${where} must change label, value, order or componentIndexes`);
270
+ }
271
+ }
272
+ return stages;
273
+ }
274
+
275
+ export function buildStageInserts(stages = [], { idFactory = () => randomUUID(), flowId } = {}) {
276
+ return stages
277
+ .map((stage, index) => ({ stage, index }))
278
+ .sort((a, b) => (a.stage.order ?? a.index) - (b.stage.order ?? b.index))
279
+ .map(({ stage, index }) => ({
280
+ stageId: idFactory(),
281
+ label: String(stage.label).trim(),
282
+ value: stage.value ?? stageValueFromLabel(stage.label),
283
+ type: 'standard',
284
+ duration: stage.duration ?? STAGE_DURATION,
285
+ ancestorArrPos: '0',
286
+ ...(flowId ? { flow: flowId } : {}),
287
+ alwaysShow: true,
288
+ order: stage.order ?? index,
289
+ system: stage.system ?? false,
290
+ componentIndexes: stage.componentIndexes ?? [],
291
+ states: stage.states ?? STAGE_STATES,
292
+ }));
293
+ }
294
+
295
+ export function buildStageUpdates(stages = []) {
296
+ return stages.map((stage) => {
297
+ const update = { stageId: stage.stageId };
298
+ if (stage.label !== undefined) update.label = String(stage.label).trim();
299
+ if (stage.value !== undefined) update.value = stage.value;
300
+ if (stage.order !== undefined) update.order = stage.order;
301
+ if (stage.componentIndexes !== undefined) update.componentIndexes = stage.componentIndexes;
302
+ return update;
303
+ });
304
+ }
305
+
306
+ /**
307
+ * `stages` is part of the same snFlowDesigner patch as actions, but placement
308
+ * has to follow the actions: `componentIndexes` name flow-step orders that must
309
+ * already exist. Creation therefore sends stages in a second patch.
310
+ */
311
+ export function buildFlowStageMutation({ flowId, inserts = [], updates = [] }) {
312
+ const parts = [];
313
+ if (inserts.length) parts.push(`insert: [${inserts.map(gqlInputObject).join(', ')}]`);
314
+ if (updates.length) parts.push(`update: [${updates.map(gqlInputObject).join(', ')}]`);
315
+ if (!parts.length) throw new Error('Flow stage patch requires at least one insert or update');
316
+ return `mutation { global { snFlowDesigner { flow(flowPatch: {flowId: ${gqlString(flowId)}, stages: {${parts.join(', ')}}}) { id stages { inserts { sysId } } } } } }`;
317
+ }
318
+
319
+ /**
320
+ * Read the catalog item's variables as a `service_catalog` flow sees them.
321
+ *
322
+ * A service_catalog trigger takes `template_catalog_item` (an sc_cat_item
323
+ * sys_id) plus `catalog_variables`, a comma-joined list of item_option_new
324
+ * sys_ids. This is the lookup Flow Designer runs when you pick the item, so the
325
+ * ids a manifest needs are the `id` values returned here.
326
+ */
327
+ export async function readCatalogItemVariables(sdk, instance, flowId, catalogItemId, { scope = 'global', includeMultiRowVariableSets = true, selectedVariables = '' } = {}) {
328
+ if (!String(catalogItemId || '').trim()) throw new Error('catalog-variables requires a catalog item sys_id');
329
+ const query = new URLSearchParams({ sysparm_transaction_scope: scope });
330
+ const response = await sdk.request(`${instance}${FLOW_ENDPOINT}/${encodeURIComponent(flowId)}/service_get_catalog_variables?${query}`, {
331
+ method: 'POST',
332
+ body: JSON.stringify({ flow_catalog_model: catalogItemId, includeMultiRowVariableSets, selectedVariables }),
333
+ });
334
+ const data = response?.result?.data;
335
+ 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');
336
+ const variables = data.availableList.map(variable => ({
337
+ id: stringValue(variable.id),
338
+ name: stringValue(variable.name),
339
+ label: stringValue(variable.label),
340
+ type: stringValue(variable.type),
341
+ mandatory: asBool(variable.mandatory),
342
+ readonly: asBool(variable.readonly),
343
+ }));
344
+ return {
345
+ flow_id: flowId,
346
+ catalog_item: catalogItemId,
347
+ count: variables.length,
348
+ variables,
349
+ // Exactly what the trigger input expects, so it can be pasted into a manifest.
350
+ catalog_variables_input: variables.map(variable => variable.id).join(','),
351
+ };
352
+ }
353
+
198
354
  export function buildFlowPatchMutation({ flowId, trigger, actions }) {
199
355
  const triggerInsert = {
200
356
  flowSysId: trigger.flowSysId,
@@ -223,12 +379,17 @@ export function buildFlowPatchMutation({ flowId, trigger, actions }) {
223
379
  return `mutation { global { snFlowDesigner { flow(${patch}) { triggerInstances { inserts { sysId } updates } actions { inserts { sysId uiUniqueIdentifier } } } } } }`;
224
380
  }
225
381
 
226
- export function buildFlowUpdateMutation({ flowId, triggerUpdates = [], actionUpdates = [] }) {
382
+ export function buildFlowUpdateMutation({ flowId, triggerUpdates = [], actionUpdates = [], stageInserts = [], stageUpdates = [] }) {
227
383
  const updates = [];
228
384
  if (triggerUpdates.length) updates.push(`triggerInstances: {update: [${triggerUpdates.map(gqlInputObject).join(', ')}]}`);
229
385
  if (actionUpdates.length) updates.push(`actions: {update: [${actionUpdates.map(gqlInputObject).join(', ')}]}`);
386
+ const stageParts = [];
387
+ if (stageInserts.length) stageParts.push(`insert: [${stageInserts.map(gqlInputObject).join(', ')}]`);
388
+ if (stageUpdates.length) stageParts.push(`update: [${stageUpdates.map(gqlInputObject).join(', ')}]`);
389
+ if (stageParts.length) updates.push(`stages: {${stageParts.join(', ')}}`);
390
+ if (!updates.length) throw new Error('Flow update mutation requires at least one change');
230
391
  const patch = `flowPatch: {flowId: ${gqlString(flowId)}, ${updates.join(', ')}}`;
231
- return `mutation { global { snFlowDesigner { flow(${patch}) { triggerInstances { updates } actions { updates } } } } }`;
392
+ return `mutation { global { snFlowDesigner { flow(${patch}) { triggerInstances { updates } actions { updates } stages { inserts { sysId } } } } } }`;
232
393
  }
233
394
 
234
395
  export async function readProcessFlow(sdk, instance, flowId, scope) {
@@ -384,6 +545,31 @@ function actionTypeIdOf(action) {
384
545
  return idValue(action?.actionTypeSysId || action?.action_type_sys_id || action?.actionType?.sys_id || action?.actionType?.sysId);
385
546
  }
386
547
 
548
+ /**
549
+ * Confirm the stages this command asked for are the ones the flow now carries.
550
+ * Matching is by generated stageId: a label-only check could pass while the
551
+ * placement landed on a different stage.
552
+ */
553
+ function assertStagesPlaced(processflow, stageInserts, flowId) {
554
+ if (!stageInserts.length) return;
555
+ const saved = stageList(processflow);
556
+ if (!saved.length) throw new Error(`Flow ${flowId} stage read-back returned no stages after placing ${stageInserts.length}`);
557
+ for (const expected of stageInserts) {
558
+ const matches = saved.filter(stage => stringValue(stage.stageId || stage.stage_id) === expected.stageId);
559
+ if (matches.length !== 1) throw new Error(`Flow ${flowId} stage "${expected.label}" (${expected.stageId}) was not uniquely present in ProcessFlow read-back`);
560
+ const savedStage = matches[0];
561
+ 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}"`);
562
+ 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}`);
563
+ if (expected.componentIndexes !== undefined) {
564
+ const savedIndexes = (Array.isArray(savedStage.componentIndexes) ? savedStage.componentIndexes : []).map(String).sort();
565
+ const expectedIndexes = expected.componentIndexes.map(String).sort();
566
+ if (JSON.stringify(savedIndexes) !== JSON.stringify(expectedIndexes)) {
567
+ throw new Error(`Flow ${flowId} stage ${expected.stageId} placement did not match the requested componentIndexes`);
568
+ }
569
+ }
570
+ }
571
+ }
572
+
387
573
  function verifyCreatedFlowReadback({ flowId, processflow, trigger, insertedTrigger, manifest, actionInstances, inserted }) {
388
574
  const returnedFlowId = stringValue(processflow.flowId || processflow.flow_id || processflow.sysId || processflow.sys_id);
389
575
  if (returnedFlowId && returnedFlowId !== flowId) throw new Error(`ProcessFlow read-back returned a different flow ID (${returnedFlowId})`);
@@ -549,8 +735,8 @@ async function resolveExistingAction(sdk, actions, requested, index) {
549
735
 
550
736
  export function validateFlowUpdateManifest(manifest) {
551
737
  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`);
738
+ const allowed = new Set(['scope', 'trigger', 'actions', 'stages']);
739
+ for (const key of Object.keys(manifest)) if (!allowed.has(key)) throw new Error(`Flow update field "${key}" is unsupported; only trigger, existing action inputs and stages may be updated`);
554
740
  if (manifest.scope !== undefined && !String(manifest.scope).trim()) throw new Error('Flow update scope must not be empty');
555
741
  if (manifest.trigger !== undefined) {
556
742
  if (!manifest.trigger || typeof manifest.trigger !== 'object' || Array.isArray(manifest.trigger)) throw new Error('Flow update trigger must be an object');
@@ -571,7 +757,8 @@ export function validateFlowUpdateManifest(manifest) {
571
757
  if (Object.keys(action.inputs).length === 0) throw new Error(`Update action ${index + 1} inputs must contain at least one changed value`);
572
758
  }
573
759
  }
574
- if (manifest.trigger === undefined && manifest.actions === undefined) throw new Error('Flow update manifest must specify trigger and/or actions');
760
+ if (manifest.trigger === undefined && manifest.actions === undefined && manifest.stages === undefined) throw new Error('Flow update manifest must specify trigger, actions and/or stages');
761
+ if (manifest.stages !== undefined) validateStages(manifest.stages, { update: true });
575
762
  return manifest;
576
763
  }
577
764
 
@@ -949,8 +1136,20 @@ export async function createFlowFromManifest(sdk, instance, inputManifest, optio
949
1136
  const inserted = insertedActions(patchResponse);
950
1137
  if (inserted.length !== actionInstances.length) throw new Error(`Flow action patch returned ${inserted.length} inserted action identities; expected ${actionInstances.length}`);
951
1138
 
1139
+ // Stages carry componentIndexes that name flow-step orders, so placement
1140
+ // runs after the actions exist — the same order Flow Designer uses.
1141
+ const stageInserts = buildStageInserts(manifest.stages || [], { idFactory, flowId });
1142
+ if (stageInserts.length) {
1143
+ const stageResponse = await mutationContext('stage_placement', readUpdateSet, snapshots, () => sdk.request(`${instance}${GRAPHQL_ENDPOINT}`, {
1144
+ method: 'POST',
1145
+ body: JSON.stringify({ query: buildFlowStageMutation({ flowId, inserts: stageInserts }), variables: {} }),
1146
+ }), updateSet => readUpdateSetCapture(sdk, updateSet, flowId));
1147
+ assertGraphQLSuccess(stageResponse, 'Flow stage placement');
1148
+ }
1149
+
952
1150
  const processflow = await readProcessFlow(sdk, instance, flowId, scope);
953
- verifyCreatedFlowReadback({ flowId, processflow, trigger, insertedTrigger, manifest, actionInstances, inserted });
1151
+ verifyCreatedFlowReadback({ flowId, processflow, trigger, insertedTrigger, manifest, actionInstances, inserted, stageInserts });
1152
+ assertStagesPlaced(processflow, stageInserts, flowId);
954
1153
  const { version } = await mutationContext('autosave_version', readUpdateSet, snapshots, () => createVerifiedFlowVersion(sdk, {
955
1154
  instance, flowId, scope, type: 'Autosave', annotation: 'JSN flow create',
956
1155
  }), updateSet => readUpdateSetCapture(sdk, updateSet, flowId));
@@ -1013,6 +1212,8 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1013
1212
  const snapshots = [];
1014
1213
  const triggerUpdates = [];
1015
1214
  const actionUpdates = [];
1215
+ const stageInserts = buildStageInserts((manifest.stages || []).filter(stage => stage.stageId === undefined), { idFactory: options.idFactory || (() => randomUUID()), flowId });
1216
+ const stageUpdates = buildStageUpdates((manifest.stages || []).filter(stage => stage.stageId !== undefined));
1016
1217
  const changedActionInputs = new Map();
1017
1218
  const actionTargets = new Map();
1018
1219
  const changes = [];
@@ -1040,7 +1241,20 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1040
1241
  changedActionInputs.set(uiId, new Set(Object.keys(requested.inputs)));
1041
1242
  for (const [input, after] of Object.entries(requested.inputs)) changes.push({ component: 'action', order: requested.order, type: requested.type, input, before: inputRawValue(inputList(existing).find(field => field.name === input)), after });
1042
1243
  }
1043
- if (triggerUpdates.length === 0 && actionUpdates.length === 0) throw new Error(`Flow ${flowId} update has no supported changes`);
1244
+ const savedStages = stageList(beforeDefinition);
1245
+ const savedStageById = new Map(savedStages.map(stage => [stringValue(stage.stageId || stage.stage_id), stage]));
1246
+ for (const update of stageUpdates) {
1247
+ const before = savedStageById.get(update.stageId);
1248
+ if (!before) throw new Error(`Flow ${flowId} has no stage ${update.stageId}; omit stageId to insert a new stage`);
1249
+ for (const [field, after] of Object.entries(update)) {
1250
+ if (field === 'stageId') continue;
1251
+ changes.push({ component: 'stage', stage: stringValue(before.label), input: field, before: before[field], after });
1252
+ }
1253
+ }
1254
+ for (const insert of stageInserts) {
1255
+ changes.push({ component: 'stage', stage: insert.label, input: 'insert', before: null, after: { order: insert.order, componentIndexes: insert.componentIndexes } });
1256
+ }
1257
+ if (triggerUpdates.length === 0 && actionUpdates.length === 0 && stageInserts.length === 0 && stageUpdates.length === 0) throw new Error(`Flow ${flowId} update has no supported changes`);
1044
1258
  if (options.preview) return {
1045
1259
  preview: true,
1046
1260
  flow: { id: flowId, name: target.flowName, status: lifecycle.status, active: lifecycle.active },
@@ -1069,15 +1283,31 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1069
1283
  try {
1070
1284
  const patchResponse = await mutationContext('trigger_and_actions_update', readUpdateSet, snapshots, () => sdk.request(`${instance}${GRAPHQL_ENDPOINT}`, {
1071
1285
  method: 'POST',
1072
- body: JSON.stringify({ query: buildFlowUpdateMutation({ flowId, triggerUpdates, actionUpdates }), variables: {} }),
1286
+ body: JSON.stringify({ query: buildFlowUpdateMutation({ flowId, triggerUpdates, actionUpdates, stageInserts, stageUpdates }), variables: {} }),
1073
1287
  }), updateSet => readUpdateSetCapture(sdk, updateSet, flowId));
1074
1288
  assertGraphQLSuccess(patchResponse, 'Flow trigger/action update');
1075
1289
  completedStage = 'patch_acknowledged';
1076
1290
  const processflow = await readProcessFlow(sdk, instance, flowId, scope);
1077
1291
  // Only requested values may differ. Preserve array order and opaque fields.
1078
- for (const field of ['flowVariables', 'flowLogicInstances', 'subFlowInstances', 'flowInputs', 'flowOutputs', 'inputs', 'outputs', 'stages']) {
1292
+ // `stages` is compared separately below: a stage edit may touch specific
1293
+ // fields, while every stage the manifest did not name must stay identical.
1294
+ for (const field of ['flowVariables', 'flowLogicInstances', 'subFlowInstances', 'flowInputs', 'flowOutputs', 'inputs', 'outputs']) {
1079
1295
  if (!isDeepStrictEqual(beforeDefinition[field], processflow[field])) throw new Error(`Flow ${flowId} changed omitted ${field}; preservation failed`);
1080
1296
  }
1297
+ if (stageInserts.length || stageUpdates.length) {
1298
+ const requestedStageIds = new Set([...stageInserts.map(stage => stage.stageId), ...stageUpdates.map(stage => stage.stageId)]);
1299
+ const untouched = definition => stageList(definition)
1300
+ .filter(stage => !requestedStageIds.has(stringValue(stage.stageId || stage.stage_id)));
1301
+ if (!isDeepStrictEqual(untouched(beforeDefinition), untouched(processflow))) throw new Error(`Flow ${flowId} changed omitted stages; preservation failed`);
1302
+ assertStagesPlaced(processflow, [...stageInserts, ...stageUpdates.map(update => ({
1303
+ stageId: update.stageId,
1304
+ label: update.label ?? stringValue(savedStageById.get(update.stageId)?.label),
1305
+ order: update.order ?? savedStageById.get(update.stageId)?.order,
1306
+ componentIndexes: update.componentIndexes,
1307
+ }))].filter(stage => stage.label !== undefined), flowId);
1308
+ } else if (!isDeepStrictEqual(beforeDefinition.stages, processflow.stages)) {
1309
+ throw new Error(`Flow ${flowId} changed omitted stages; preservation failed`);
1310
+ }
1081
1311
  if (!triggerUpdate && !isDeepStrictEqual(beforeDefinition.triggerInstances, processflow.triggerInstances)) throw new Error(`Flow ${flowId} changed omitted triggerInstances`);
1082
1312
  const maskActions = definition => findExistingActions(definition).map(action => {
1083
1313
  const copy = clone(action);
@@ -1,3 +1,5 @@
1
+ import { AppError, CodeAPI } from './errors.js';
2
+
1
3
  // Flow Designer's safeEdit lease is separate from publishing and artifact deletion.
2
4
  // The provider exposes a user-level lock, not an operation token: refuse even a
3
5
  // same-user existing lease so this CLI cannot release an open designer session.
@@ -7,21 +9,42 @@ export async function flowSafeEditRequest(sdk, instance, flowId, operation, last
7
9
  const selection = operation === 'delete' ? 'deleteResult{deleteSuccess id}' : `status{canUserEdit currentEditor${operation === 'upsert' ? ' clientFlowStale' : ''}}`;
8
10
  const query = `${operation === 'read' ? 'query' : 'mutation'} {global {snFlowDesigner {safeEdit(safeEditInput:{${input}}){${selection}}}}}`;
9
11
  const response = await sdk.request(`${instance}/api/now/graphql`, { method: 'POST', body: JSON.stringify({ query, variables: {} }) });
10
- if (response.errors?.length) throw new Error(`Flow safe edit ${operation}: ${response.errors.map(error => error.message).join('; ')}`);
12
+ if (response.errors?.length) throw new AppError(CodeAPI, `Flow safe edit ${operation}: ${response.errors.map(error => error.message).join('; ')}`);
11
13
  const result = response.data?.global?.snFlowDesigner?.safeEdit;
12
- if (!result) throw new Error(`Flow safe edit ${operation} returned no result`);
14
+ if (!result) throw new AppError(CodeAPI, `Flow safe edit ${operation} returned no result`);
13
15
  return result;
14
16
  }
15
17
 
18
+ export async function readFlowSafeEditStatus(sdk, instance, flowId) {
19
+ const { status } = await flowSafeEditRequest(sdk, instance, flowId, 'read');
20
+ if (!status || typeof status.canUserEdit !== 'boolean' || !(status.currentEditor == null || typeof status.currentEditor === 'string')) throw new AppError(CodeAPI, 'Unreadable safe edit status');
21
+ return status;
22
+ }
23
+
24
+ // The provider's `delete` only ever releases the calling user's own session, so
25
+ // recovery needs no ownership guess. It stays explicit anyway: releasing a lease
26
+ // that a live Flow Designer tab owns makes that editor's next save fail.
27
+ export async function releaseOwnFlowSafeEdit(sdk, instance, flowId) {
28
+ const before = await readFlowSafeEditStatus(sdk, instance, flowId);
29
+ const describe = status => `canUserEdit=${status.canUserEdit}, currentEditor=${JSON.stringify(status.currentEditor ?? null)}`;
30
+ if (!before.canUserEdit && !before.currentEditor) return { released: false, before, after: before };
31
+ const { deleteResult } = await flowSafeEditRequest(sdk, instance, flowId, 'delete');
32
+ if (deleteResult?.deleteSuccess !== true || deleteResult.id !== flowId) {
33
+ throw new AppError(CodeAPI, `Flow ${flowId} safe edit release was not confirmed by the provider (deleteSuccess=${JSON.stringify(deleteResult?.deleteSuccess ?? null)}, id=${JSON.stringify(deleteResult?.id ?? null)}); no retry attempted. Status before release: ${describe(before)}.`);
34
+ }
35
+ const after = await readFlowSafeEditStatus(sdk, instance, flowId);
36
+ if (after.canUserEdit || after.currentEditor) throw new AppError(CodeAPI, `Flow ${flowId} release was acknowledged, but readback still reports an edit session (${describe(after)}). Inspect the exact flow and Flow Designer session before retrying.`);
37
+ return { released: true, before, after };
38
+ }
39
+
16
40
  export async function withFlowSafeEdit(sdk, instance, flowId, lastUpdated, operation) {
17
41
  if (typeof lastUpdated !== 'string' || !lastUpdated) throw new Error(`Flow ${flowId} has no authoritative updated timestamp; safe edit refused`);
18
- const read = async () => {
19
- const { status } = await flowSafeEditRequest(sdk, instance, flowId, 'read');
20
- if (!status || typeof status.canUserEdit !== 'boolean' || !(status.currentEditor == null || typeof status.currentEditor === 'string')) throw new Error('Unreadable safe edit status');
21
- return status;
22
- };
42
+ const read = () => readFlowSafeEditStatus(sdk, instance, flowId);
23
43
  const before = await read();
24
- if (before.canUserEdit || before.currentEditor) throw new Error(`Flow ${flowId} already has an existing edit session/editor; close it in Flow Designer before retrying. No lock changed.`);
44
+ // Refuse any reported session, including one this same user holds: releasing
45
+ // it would close a Flow Designer tab this CLI never opened, so recovery stays
46
+ // an explicit command (`jsn flows unlock`) rather than an implicit takeover.
47
+ if (before.canUserEdit || before.currentEditor) throw new Error(`Flow ${flowId} already has an existing edit session/editor (canUserEdit=${before.canUserEdit}, currentEditor=${JSON.stringify(before.currentEditor ?? null)}); close it in Flow Designer before retrying, or release your own stale session with \`jsn flows unlock ${flowId}\`. No lock changed.`);
25
48
  let status;
26
49
  try {
27
50
  ({ status } = await flowSafeEditRequest(sdk, instance, flowId, 'upsert', lastUpdated));
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
+
package/src/helpers.js CHANGED
@@ -185,6 +185,29 @@ function getRawValue(val) {
185
185
  return String(val);
186
186
  }
187
187
 
188
+ /**
189
+ * Does the value supplied in --data match what the API stored for a field?
190
+ *
191
+ * The Table API accepts both choice values and their display labels
192
+ * ("true" and "True", "ignore" and "Leave alone"), so a successful write
193
+ * must not be reported as dropped just because the caller supplied the
194
+ * label. Matches the raw value exactly, or the display label
195
+ * case-insensitively when the label differs from the raw value.
196
+ */
197
+ function matchesPersisted(sent, val) {
198
+ if (val == null) return sent === '';
199
+ if (typeof val !== 'object') return String(val) === sent;
200
+
201
+ const raw = val.value == null ? null : String(val.value);
202
+ const display = val.display_value == null ? null : String(val.display_value);
203
+
204
+ if (raw != null && raw === sent) return true;
205
+ if (display && display !== raw) {
206
+ return display.toLowerCase() === sent.toLowerCase();
207
+ }
208
+ return false;
209
+ }
210
+
188
211
  /**
189
212
  * Normalize a value the user supplied in --data for comparison against
190
213
  * what the API persisted. Objects like {"value": "<sys_id>"} are unwrapped.
@@ -240,7 +263,7 @@ export async function verifyWriteBack(app, table, sysID, sentData) {
240
263
  for (const field of fields) {
241
264
  const sent = normalizeSupplied(sentData[field]);
242
265
  const got = getRawValue(persisted[field]);
243
- if (sent !== got) {
266
+ if (!matchesPersisted(sent, persisted[field])) {
244
267
  mismatches.push({ field, sent, got });
245
268
  }
246
269
  }
@@ -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'],
package/src/sdk.js CHANGED
@@ -164,7 +164,7 @@ export class SDKClient {
164
164
 
165
165
  async _performAuthenticatedRequest(endpoint, opts, {
166
166
  timeout = this.timeout, prepare, skipOAuthSession = false, normalizeErrors = false,
167
- allowMutationReplay = false,
167
+ allowMutationReplay = false, stateful = false,
168
168
  }, consume = (response) => response) {
169
169
  const method = String(opts.method || 'GET').toUpperCase();
170
170
  for (let attempt = 0; attempt <= MAX_SESSION_REPLAYS; attempt++) {
@@ -201,7 +201,7 @@ export class SDKClient {
201
201
  if (attempt >= MAX_SESSION_REPLAYS) throw this._authFailure(rejection);
202
202
  // A write or stateful processor is only replayed when the rejection
203
203
  // provably happened before execution.
204
- if (!canReplayAfterRecovery(rejection, { method, allowMutationReplay })) {
204
+ if (!canReplayAfterRecovery(rejection, { method, stateful, allowMutationReplay })) {
205
205
  throw this._unsafeReplayError(rejection, endpoint, method);
206
206
  }
207
207
  // Browser renewal has its own existing hard timeout. Never leave a
@@ -310,10 +310,13 @@ export class SDKClient {
310
310
  }
311
311
 
312
312
  async request(endpoint, opts = {}) {
313
- const { timeout = this.timeout, readOnly = false, touchLastSeen, domain = this.domain, ...requestOptions } = opts;
313
+ // Some provider mutations are GET-shaped. Keep this local replay policy
314
+ // out of fetch options rather than treating their HTTP method as read-only.
315
+ const { timeout = this.timeout, readOnly = false, stateful = false, touchLastSeen, domain = this.domain, ...requestOptions } = opts;
314
316
  if (readOnly && (requestOptions.method || 'GET').toUpperCase() !== 'GET') throw new Error('Read-only SDK requests require GET');
315
317
  return this._withAuthenticatedRequest(endpoint, requestOptions, {
316
318
  timeout,
319
+ stateful,
317
320
  normalizeErrors: true,
318
321
  prepare: (req) => {
319
322
  req.headers.set('Accept', 'application/json');
@@ -71,10 +71,10 @@ export function classifyAuthRejection(response, { bodyText = '' } = {}) {
71
71
  * login pages are strong evidence for reads; a write is replayed only when the
72
72
  * caller opted in explicitly (none of JSN's own write paths do).
73
73
  */
74
- export function canReplayAfterRecovery(rejection, { method = 'GET', allowMutationReplay = false } = {}) {
74
+ export function canReplayAfterRecovery(rejection, { method = 'GET', stateful = false, allowMutationReplay = false } = {}) {
75
75
  if (!rejection) return false;
76
76
  if (rejection.kind === 'http_401') return true;
77
- return isSafeMethod(method) || allowMutationReplay === true;
77
+ return (!stateful && isSafeMethod(method)) || allowMutationReplay === true;
78
78
  }
79
79
 
80
80
  /**
package/src/store.js CHANGED
@@ -475,7 +475,7 @@ export async function dispatchOperation(sdk, plan) {
475
475
  const path = plan.operation === 'update' ? UPDATE_PATH : INSTALL_PATH;
476
476
  const params = new URLSearchParams({ app_id: plan.app.sys_id, version: plan.requested_version });
477
477
  if (plan.operation === 'install') params.set('load_demo_data', String(Boolean(plan.demo_data)));
478
- const response = await sdk.request(`${sdk.baseURL}${path}?${params}`, { method: 'GET' });
478
+ const response = await sdk.request(`${sdk.baseURL}${path}?${params}`, { method: 'GET', stateful: true });
479
479
  const result = response?.result;
480
480
  if (!result || typeof result !== 'object') {
481
481
  throw errAPI(200, `The ${plan.operation} request returned no result, so the application state is unknown. Inspect the application before retrying.`);
@@ -513,7 +513,9 @@ export async function operationStatus(sdk, trackerId) {
513
513
  // version it acted on; it is the only place a failed submission says what it
514
514
  // tried to do.
515
515
  const detail = storeText(result, 'status_detail');
516
- const terminal = (Number.isFinite(percent) && percent >= 100) || status === '3' || Boolean(error);
516
+ // CICD states are pending=0, running=1, successful=2, failed=3,
517
+ // canceled=4. Percentage is progress, not an operation verdict.
518
+ const terminal = ['2', '3', '4'].includes(status) || Boolean(error);
517
519
  return {
518
520
  tracker_id: id,
519
521
  status,
@@ -523,7 +525,7 @@ export async function operationStatus(sdk, trackerId) {
523
525
  percent_complete: Number.isFinite(percent) ? percent : null,
524
526
  error: error || null,
525
527
  terminal,
526
- succeeded: terminal && !error && status !== '3',
528
+ succeeded: status === '2' && !error,
527
529
  };
528
530
  }
529
531
 
@@ -270,7 +270,10 @@ export async function listPreviewProblems(sdk, sysID, { limit = 500 } = {}) {
270
270
  * Refuse to continue while the platform still considers preview problems
271
271
  * unresolved. jsn never accepts, skips, or ignores one on the operator's behalf.
272
272
  */
273
- export function assertNoUnresolvedProblems({ problems, unresolved }) {
273
+ export function assertNoUnresolvedProblems({ problems, unresolved, truncated }) {
274
+ if (truncated) {
275
+ throw errUsage('Refusing to commit: the preview problem list is truncated. Unread problems may remain unresolved. Review and commit this set in ServiceNow; jsn cannot establish that every problem is resolved.');
276
+ }
274
277
  if (!unresolved.length) return;
275
278
  const lines = unresolved.slice(0, 10).map((problem) => {
276
279
  const target = problem.missing_item_table