@jacebenson/jsn 5.4.0-dev.141.1 → 5.4.0-dev.143.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.141.1",
3
+ "version": "5.4.0-dev.143.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": {
@@ -9,6 +9,7 @@ import { createFlowFromManifest, updateFlowFromManifest, readCurrentUpdateSet }
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';
12
+ import { releaseOwnFlowSafeEdit } from '../flow-safe-edit.js';
12
13
  import { errUsage } from '../errors.js';
13
14
  import { cancelled, pickDesignerRecord, guidedFlowCreate, guidedFlowEdit, guidedFlowTestRecord, hasDefinitionData, confirmDesignerMutation } from '../flow-designer-interactive.js';
14
15
 
@@ -24,6 +25,7 @@ const FLOW_COMMANDS = [
24
25
  { name: 'create', description: 'Create a draft flow: guided in a terminal, JSON manifest in scripts' },
25
26
  { name: 'update [identifier]', description: 'Update a draft, or a published flow whose definition reports write access (alias: edit)' },
26
27
  { name: 'doctor', description: 'Check whether this instance can publish flows at all' },
28
+ { name: 'unlock [identifier]', description: 'Release this user\'s stale safe-edit session (orphaned lease) after a failed update' },
27
29
  { name: 'delete [identifier]', description: 'Delete a flow (not implemented: use the Flow Designer UI)' },
28
30
  ];
29
31
 
@@ -46,7 +48,7 @@ function triggerGuidance(trigger) {
46
48
  };
47
49
  }
48
50
 
49
- declareCapabilities('flows', { mutationSubcommands: ['create', 'update', 'edit', 'delete', 'publish', 'test'] });
51
+ declareCapabilities('flows', { mutationSubcommands: ['create', 'update', 'edit', 'delete', 'publish', 'test', 'unlock'] });
50
52
 
51
53
  function renderChecks(checks) {
52
54
  return checks.map((c) => {
@@ -383,6 +385,31 @@ export function flowsCmd(wrap) {
383
385
  });
384
386
  }),
385
387
  })
388
+ .command({
389
+ 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.',
391
+ builder: (y) => y
392
+ .option('force', { type: 'boolean', default: false, describe: 'Skip confirmation' }),
393
+ handler: wrap(async (argv, app) => {
394
+ app.requireInstance();
395
+ const identifier = await pickFlow(argv, app);
396
+ if (identifier === undefined) return;
397
+ const sysID = unwrapSysId(await resolveRecord(app.sdk, {
398
+ table: 'sys_hub_flow', identifier, matchField: 'name', resource: 'Flow',
399
+ }));
400
+ await confirmDesignerMutation(argv, app, `Release your Flow Designer safe-edit session on flow ${identifier}? If this flow is open in Flow Designer, that editor's next save will fail.`);
401
+ const result = await releaseOwnFlowSafeEdit(app.sdk, app.getEffectiveInstance(), sysID);
402
+ const state = status => `canUserEdit=${status.canUserEdit}, currentEditor=${JSON.stringify(status.currentEditor ?? null)}`;
403
+ return app.ok({ ...result, flow: { id: sysID, name: identifier } }, {
404
+ summary: result.released
405
+ ? `Released this user's safe edit session on flow ${identifier} (${sysID}): ${state(result.before)} -> ${state(result.after)}`
406
+ : `No safe edit session to release on flow ${identifier} (${sysID}): ${state(result.before)}`,
407
+ breadcrumbs: result.released
408
+ ? [{ action: 'update', cmd: `jsn flows update ${sysID}`, description: 'Retry the edit' }]
409
+ : [{ action: 'show', cmd: `jsn flows show ${sysID}`, description: 'Inspect the flow' }],
410
+ });
411
+ }),
412
+ })
386
413
  .command({
387
414
  command: 'delete [identifier]',
388
415
  describe: 'Delete a flow (not yet implemented)',
@@ -145,6 +145,10 @@ function emitList(app, argv, page) {
145
145
  }
146
146
 
147
147
  async function runLifecycle(argv, app, operation) {
148
+ // Validate wait controls before any submission. A usage error after dispatch
149
+ // hides an operation that may already be changing the instance.
150
+ const timeoutMs = argv.wait ? boundedTimeout(argv.timeout) * 1000 : undefined;
151
+ const pollIntervalMs = argv.wait ? boundedPoll(argv.pollInterval) * 1000 : undefined;
148
152
  const prepare = operation === 'install' ? prepareInstall : prepareUpdate;
149
153
  const plan = await prepare(app.sdk, argv.application, operation === 'install'
150
154
  ? { version: argv.version, demoData: argv.demoData === true }
@@ -177,8 +181,6 @@ async function runLifecycle(argv, app, operation) {
177
181
  });
178
182
  return;
179
183
  }
180
- const timeoutMs = boundedTimeout(argv.timeout) * 1000;
181
- const pollIntervalMs = boundedPoll(argv.pollInterval) * 1000;
182
184
  let progress;
183
185
  try {
184
186
  progress = await waitForOperation(app.sdk, started.tracker_id, { pollIntervalMs, timeoutMs });
package/src/errors.js CHANGED
@@ -309,6 +309,10 @@ export function renderAppError(err, { app = null, argv = null, identifier = '' }
309
309
  return { stream: 'stderr', text, exitCode: 2 };
310
310
  }
311
311
 
312
+ if (code === CodeAPI && resolveJsonMode(app, argv) && app) {
313
+ return { stream: 'stdout', text: null, exitCode: 1, appErr: true };
314
+ }
315
+
312
316
  if (code === 'system_error') {
313
317
  return { stream: 'stderr', text: `Error (system): ${err.message}\n`, exitCode: 3 };
314
318
  }
@@ -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/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
@@ -46,10 +46,12 @@ export function numberWorkflowSteps(activities, transitions, startId, components
46
46
  }
47
47
  }
48
48
  for (const activity of stable) if (!visited.has(activity.sys_id)) add(activity, false);
49
- // Stable partition after traversal; fallback retains its disclosed name/ID order.
49
+ // Keep the observed traversal ahead of the stable detached appendix.
50
+ // Only reached terminal activities move behind other reached activities.
50
51
  if (!fallback_reason) {
51
- steps.sort((a, b) => Number(outgoing.get(a.sys_id).length === 0)
52
- - Number(outgoing.get(b.sys_id).length === 0));
52
+ steps.sort((a, b) => Number(b.reached_from_start) - Number(a.reached_from_start)
53
+ || (a.reached_from_start ? Number(outgoing.get(a.sys_id).length === 0)
54
+ - Number(outgoing.get(b.sys_id).length === 0) : 0));
53
55
  steps.forEach((step, index) => { step.number = index + 1; });
54
56
  }
55
57
  const byId = new Map(steps.map(step => [step.sys_id, step]));