@jacebenson/jsn 5.2.0-dev.133.1 → 5.2.0-dev.134.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.2.0-dev.133.1",
3
+ "version": "5.2.0-dev.134.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": {
@@ -10,10 +10,11 @@ import { AppError, CodeConfirmationRequired, errAPI, errUsage, errConfirmationRe
10
10
  import { declareCapabilities } from '../capabilities.js';
11
11
  import { resolveScope } from './scopes.js';
12
12
  import { unwrapSysId } from '../resolve-record.js';
13
+ import { assertNoUnresolvedProblems, DEFAULT_OPERATION_TIMEOUT_MS } from '../update-set-apply.js';
13
14
 
14
15
  declareCapabilities('updatesets', {
15
- mutationSubcommands: ['create', 'set', 'complete', 'ignore', 'parent', 'import', 'reopen'],
16
- mutationContextExemptSubcommands: ['create', 'set', 'import', 'reopen'],
16
+ mutationSubcommands: ['create', 'set', 'complete', 'ignore', 'parent', 'import', 'reopen', 'preview', 'commit'],
17
+ mutationContextExemptSubcommands: ['create', 'set', 'import', 'reopen', 'preview', 'commit'],
17
18
  localPreviewSubcommands: ['import'],
18
19
  });
19
20
 
@@ -97,6 +98,121 @@ export async function resolveUpdateSetByName(app, name) {
97
98
  throw errUsage(`Multiple update sets named "${name}" (${records.length}): ${scopes}.${scopeNote}\nRun bare "jsn updatesets set" and pick by scope.`);
98
99
  }
99
100
 
101
+ const RETRIEVED_FIELDS = 'sys_id,name,state,remote_sys_id,update_set,sys_created_on,sys_updated_on';
102
+
103
+ function remoteState(record) {
104
+ const raw = record?.state;
105
+ return String(raw?.value ?? raw ?? '').toLowerCase();
106
+ }
107
+
108
+ /**
109
+ * Resolve a *retrieved* update set (sys_remote_update_set) by exact name or
110
+ * sys_id. Imported XML lives here; local capture sets live in sys_update_set.
111
+ * @returns {Promise<object>} raw record
112
+ */
113
+ export async function resolveRetrievedUpdateSet(app, identifier) {
114
+ assertSafeExactMatch(identifier);
115
+ const isSysID = /^[0-9a-f]{32}$/i.test(identifier);
116
+ const params = new URLSearchParams();
117
+ params.set('sysparm_query', isSysID ? `sys_id=${identifier}` : `name=${identifier}`);
118
+ params.set('sysparm_limit', isSysID ? '1' : '20');
119
+ params.set('sysparm_display_value', 'all');
120
+ params.set('sysparm_fields', RETRIEVED_FIELDS);
121
+ const records = await app.sdk.list('sys_remote_update_set', params);
122
+ if (!records.length) {
123
+ throw errUsage(
124
+ `Retrieved update set not found: ${identifier}`,
125
+ `Load the XML first (jsn updatesets import <file>), or pass the sys_id of the retrieved set.`,
126
+ );
127
+ }
128
+ if (records.length > 1) {
129
+ throw errUsage(`Multiple retrieved update sets named "${identifier}". Pass the sys_id instead:\n${records.map((r) => ` ${getStringField(r, 'sys_id')} ${remoteState(r)}`).join('\n')}`);
130
+ }
131
+ return records[0];
132
+ }
133
+
134
+ async function fetchRetrievedUpdateSet(app, sysID) {
135
+ const params = new URLSearchParams();
136
+ params.set('sysparm_query', `sys_id=${sysID}`);
137
+ params.set('sysparm_limit', '1');
138
+ params.set('sysparm_display_value', 'all');
139
+ params.set('sysparm_fields', RETRIEVED_FIELDS);
140
+ const [record] = await app.sdk.list('sys_remote_update_set', params);
141
+ return record || null;
142
+ }
143
+
144
+ /**
145
+ * Confirmation gate shared by updatesets mutations. Automation gets a
146
+ * confirmation-required error with a rerun command instead of a prompt.
147
+ * @returns {Promise<boolean>} false when the human declined
148
+ */
149
+ async function confirmUpdateSetMutation(argv, app, question, rerun) {
150
+ if (argv.yes) return true;
151
+ if (!canPrompt() || argv.json || argv.get || (argv.format && argv.format !== FormatAuto)) {
152
+ throw new AppError(CodeConfirmationRequired, `${question} — confirmation required. Pass --yes after approving this target.`,
153
+ `Rerun: ${buildRerunCommand(argv, { rerun })}`);
154
+ }
155
+ return confirm({ message: question, default: false });
156
+ }
157
+
158
+ function timeoutFrom(argv) {
159
+ const seconds = Number(argv.timeout ?? DEFAULT_OPERATION_TIMEOUT_MS / 1000);
160
+ if (!Number.isFinite(seconds) || seconds <= 0) throw errUsage('--timeout must be a positive number of seconds');
161
+ return Math.round(seconds * 1000);
162
+ }
163
+
164
+ /**
165
+ * The platform records the local update set a commit produced on the retrieved
166
+ * record itself (`sys_remote_update_set.update_set`). Prefer that exact
167
+ * reference; only fall back to a name lookup when it is absent.
168
+ */
169
+ function localReferenceID(reference) {
170
+ if (!reference) return '';
171
+ if (typeof reference === 'object') {
172
+ const value = String(reference.value ?? '').trim();
173
+ if (/^[0-9a-f]{32}$/i.test(value)) return value;
174
+ const link = String(reference.link ?? '');
175
+ const match = link.match(/\/([0-9a-f]{32})(?:\/)?$/i);
176
+ return match ? match[1] : '';
177
+ }
178
+ return /^[0-9a-f]{32}$/i.test(String(reference).trim()) ? String(reference).trim() : '';
179
+ }
180
+
181
+ /**
182
+ * Find the local update set a commit created. Ambiguity is reported, not
183
+ * guessed: duplicate names are legitimate on ServiceNow.
184
+ */
185
+ async function findLocalUpdateSet(app, name, reference) {
186
+ const referenceID = localReferenceID(reference);
187
+ if (referenceID) {
188
+ try {
189
+ const record = await app.sdk.get('sys_update_set', referenceID);
190
+ if (record) {
191
+ return {
192
+ sys_id: getStringField(record, 'sys_id') || referenceID,
193
+ name: getStringField(record, 'name') || name,
194
+ state: String(record.state?.value ?? record.state ?? ''),
195
+ ambiguous: false,
196
+ };
197
+ }
198
+ } catch { /* fall back to the name lookup */ }
199
+ }
200
+ const params = new URLSearchParams();
201
+ params.set('sysparm_query', `name=${name}^ORDERBYDESCsys_created_on`);
202
+ params.set('sysparm_display_value', 'all');
203
+ params.set('sysparm_limit', '2');
204
+ params.set('sysparm_fields', 'sys_id,name,state,sys_created_on');
205
+ try {
206
+ const records = await app.sdk.list('sys_update_set', params);
207
+ if (records.length === 1) {
208
+ return { sys_id: getStringField(records[0], 'sys_id'), name: getStringField(records[0], 'name'), state: String(records[0].state?.value ?? records[0].state ?? ''), ambiguous: false };
209
+ }
210
+ return { ambiguous: true, count: records.length, note: records.length ? 'Multiple local update sets share this name' : 'No local update set with this name was found' };
211
+ } catch (error) {
212
+ return { ambiguous: false, unverified: true, note: `Could not read local update sets: ${error.message}` };
213
+ }
214
+ }
215
+
100
216
 
101
217
  function rawReferenceId(value) {
102
218
  if (!value) return '';
@@ -546,8 +662,23 @@ export function updateSetsCmd(wrap) {
546
662
  builder: y => y
547
663
  .positional('file', { type: 'string', describe: 'Update set XML export' })
548
664
  .option('dry-run', { type: 'boolean', describe: 'Inspect locally without any instance requests' })
549
- .option('yes', { type: 'boolean', describe: 'Confirm loading the displayed XML into the selected target' }),
665
+ .option('yes', { type: 'boolean', describe: 'Confirm loading the displayed XML into the selected target' })
666
+ .option('name', { type: 'string', describe: 'Unsupported: the set keeps the name in its XML envelope' })
667
+ .option('local', { type: 'boolean', describe: 'Unsupported: import always loads a retrieved update set' })
668
+ .option('state', { type: 'string', describe: 'Unsupported: import never changes state' }),
550
669
  handler: wrap(async (argv, app) => {
670
+ // The proposed import modifiers are refused explicitly so none of
671
+ // them can silently rewrite identity, convert the target table, or
672
+ // flip state. Preview/commit/reopen are the supported transitions.
673
+ if (argv.name !== undefined) {
674
+ throw errUsage('Import cannot rename a retrieved update set: its name, sys_id, and remote_sys_id come from the exported envelope, so rewriting them would change the set\'s identity.\nLoad it unchanged, then rename the retrieved set in ServiceNow if you need a different name.');
675
+ }
676
+ if (argv.local) {
677
+ throw errUsage('Import always creates a retrieved update set (sys_remote_update_set); it does not convert XML into a local capture set.\nPreview and commit it to apply the changes (jsn updatesets preview / commit).');
678
+ }
679
+ if (argv.state !== undefined) {
680
+ throw errUsage('Import never sets state. A loaded retrieved set is previewed and committed explicitly; a local set is reopened with "jsn updatesets reopen".');
681
+ }
551
682
  const stat = await fs.promises.stat(argv.file);
552
683
  if (!stat.isFile() || stat.size > MAX_UPDATE_SET_BYTES) throw errUsage('Expected an XML file no larger than 50 MiB');
553
684
  const xml = await fs.promises.readFile(argv.file, 'utf8');
@@ -556,15 +687,123 @@ export function updateSetsCmd(wrap) {
556
687
  if (argv.dryRun) return app.ok({ ...summary, members, dry_run: true }, { summary: `XML: ${inspection.name}; ${inspection.count} updates (local inspection only)` });
557
688
  app.requireInstance();
558
689
  const question = `Load "${inspection.name}" (${inspection.count} updates) into ${app.getEffectiveInstance()} as a retrieved update set? This does not commit its changes.`;
559
- if (!argv.yes) {
560
- if (!canPrompt() || argv.json || argv.get || (argv.format && argv.format !== FormatAuto)) {
561
- throw new AppError(CodeConfirmationRequired, `${question} — confirmation required. Pass --yes after approving this target.`,
562
- `Rerun: ${buildRerunCommand(argv, { rerun: ['updatesets', 'import', argv.file, '--yes'] })}`);
563
- }
564
- if (!await confirm({ message: question, default: false })) return;
565
- }
690
+ if (!await confirmUpdateSetMutation(argv, app, question, ['updatesets', 'import', argv.file, '--yes'])) return;
566
691
  const result = await app.sdk.importUpdateSet(xml, inspection, path.basename(argv.file));
567
- app.ok({ ...summary, ...result, committed: false }, { summary: `Loaded retrieved update set "${inspection.name}" (${result.count} updates); not committed` });
692
+ app.ok({ ...summary, ...result, committed: false }, {
693
+ summary: `Loaded retrieved update set "${inspection.name}" (${result.count} updates); not committed`,
694
+ breadcrumbs: [
695
+ { action: 'preview', cmd: `jsn updatesets preview ${quoteShellArg(result.sys_id)}`, description: 'Preview against this instance before committing' },
696
+ { action: 'problems', cmd: `jsn updatesets problems ${quoteShellArg(result.sys_id)}`, description: 'Review preview problems' },
697
+ ],
698
+ });
699
+ }),
700
+ })
701
+ .command({
702
+ command: 'preview <name>',
703
+ describe: 'Run the platform preview for a loaded retrieved update set and report its problems',
704
+ builder: y => y
705
+ .positional('name', { type: 'string', describe: 'Retrieved update set name or sys_id' })
706
+ .option('yes', { type: 'boolean', describe: 'Confirm starting the preview on the selected target' })
707
+ .option('timeout', { type: 'number', describe: 'Seconds to wait for the preview tracker (default 600)' }),
708
+ handler: wrap(async (argv, app) => {
709
+ app.requireInstance();
710
+ const target = await resolveRetrievedUpdateSet(app, argv.name);
711
+ const sysID = getStringField(target, 'sys_id');
712
+ const state = remoteState(target);
713
+ if (!['loaded', 'previewed'].includes(state)) {
714
+ throw errUsage(`Cannot preview a retrieved update set in state "${state}"; expected loaded or previewed.\nInspect it first: jsn records get sys_remote_update_set ${sysID}`);
715
+ }
716
+ const question = `Preview retrieved update set "${getStringField(target, 'name')}" (state: ${state}) on ${app.getEffectiveInstance()}? Preview does not commit changes.`;
717
+ if (!await confirmUpdateSetMutation(argv, app, question, ['updatesets', 'preview', sysID, '--yes'])) return;
718
+ const progress = await app.sdk.previewUpdateSet(sysID, { timeoutMs: timeoutFrom(argv) });
719
+ const verified = await fetchRetrievedUpdateSet(app, sysID);
720
+ if (!verified || remoteState(verified) !== 'previewed') {
721
+ throw errAPI(200, `Preview reported "${progress.label}" but the retrieved update set is in state "${verified ? remoteState(verified) || 'unknown' : 'unreadable'}".\nInspect it in ServiceNow before committing; jsn will not commit a set the platform has not previewed.`);
722
+ }
723
+ const { problems, count, unresolved, truncated } = await app.sdk.listUpdateSetPreviewProblems(sysID);
724
+ app.ok({
725
+ update_set: getStringField(target, 'name'),
726
+ sys_id: sysID,
727
+ state: 'previewed',
728
+ preview: { status: progress.label, percent_complete: progress.percent_complete, message: progress.message, tracked: progress.tracked !== false },
729
+ problems: count,
730
+ unresolved: unresolved.length,
731
+ truncated,
732
+ problems_detail: problems,
733
+ }, {
734
+ summary: `Previewed retrieved update set "${getStringField(target, 'name')}": ${unresolved.length} unresolved problem(s) of ${count}`,
735
+ breadcrumbs: unresolved.length
736
+ ? [{ action: 'problems', cmd: `jsn updatesets problems ${quoteShellArg(sysID)}`, description: 'Review the problems a human must resolve' }]
737
+ : [{ action: 'commit', cmd: `jsn updatesets commit ${quoteShellArg(sysID)} --yes`, description: 'Commit after reviewing the preview' }],
738
+ });
739
+ }),
740
+ })
741
+ .command({
742
+ command: 'problems <name>',
743
+ aliases: ['preview-problems'],
744
+ describe: 'List preview problems for a retrieved update set (read-only; never resolves them)',
745
+ builder: y => y
746
+ .positional('name', { type: 'string', describe: 'Retrieved update set name or sys_id' })
747
+ .option('include-resolved', { type: 'boolean', describe: 'Include problems a human already accepted or skipped' }),
748
+ handler: wrap(async (argv, app) => {
749
+ app.requireInstance();
750
+ const target = await resolveRetrievedUpdateSet(app, argv.name);
751
+ const sysID = getStringField(target, 'sys_id');
752
+ const { problems, count, unresolved, truncated } = await app.sdk.listUpdateSetPreviewProblems(sysID);
753
+ const shown = argv.includeResolved ? problems : unresolved;
754
+ app.ok({
755
+ update_set: getStringField(target, 'name'),
756
+ sys_id: sysID,
757
+ state: remoteState(target),
758
+ count,
759
+ unresolved: unresolved.length,
760
+ truncated,
761
+ problems: shown,
762
+ }, {
763
+ summary: `${unresolved.length} unresolved preview problem(s) for "${getStringField(target, 'name')}" (${count} total)`,
764
+ breadcrumbs: [{ action: 'show', cmd: `jsn records get sys_remote_update_set ${quoteShellArg(sysID)}`, description: 'Open the retrieved update set record' }],
765
+ });
766
+ }),
767
+ })
768
+ .command({
769
+ command: 'commit <name>',
770
+ describe: 'Commit a previewed retrieved update set once its preview problems are resolved',
771
+ builder: y => y
772
+ .positional('name', { type: 'string', describe: 'Retrieved update set name or sys_id' })
773
+ .option('yes', { type: 'boolean', describe: 'Confirm applying the update set to the selected target' })
774
+ .option('timeout', { type: 'number', describe: 'Seconds to wait for the commit tracker (default 600)' }),
775
+ handler: wrap(async (argv, app) => {
776
+ app.requireInstance();
777
+ const target = await resolveRetrievedUpdateSet(app, argv.name);
778
+ const sysID = getStringField(target, 'sys_id');
779
+ const name = getStringField(target, 'name');
780
+ const state = remoteState(target);
781
+ if (state === 'loaded') {
782
+ throw errUsage(`Retrieved update set "${name}" has not been previewed yet.\nRun: jsn updatesets preview ${quoteShellArg(sysID)}`);
783
+ }
784
+ if (state !== 'previewed') {
785
+ throw errUsage(`Cannot commit a retrieved update set in state "${state}"; expected previewed.`);
786
+ }
787
+ const previewProblems = await app.sdk.listUpdateSetPreviewProblems(sysID);
788
+ assertNoUnresolvedProblems(previewProblems);
789
+ const question = `Commit retrieved update set "${name}" (${previewProblems.count} preview problem(s), none unresolved) to ${app.getEffectiveInstance()}? This applies its changes to the instance.`;
790
+ if (!await confirmUpdateSetMutation(argv, app, question, ['updatesets', 'commit', sysID, '--yes'])) return;
791
+ const progress = await app.sdk.commitUpdateSet(sysID, { timeoutMs: timeoutFrom(argv) });
792
+ const verified = await fetchRetrievedUpdateSet(app, sysID);
793
+ if (!verified || remoteState(verified) !== 'committed') {
794
+ throw errAPI(200, `Commit reported "${progress.label}" but the retrieved update set is in state "${verified ? remoteState(verified) || 'unknown' : 'unreadable'}".\nThe commit may still be running; inspect Retrieved Update Sets on the target before retrying. jsn does not retry it.`);
795
+ }
796
+ const local = await findLocalUpdateSet(app, name, verified.update_set);
797
+ app.ok({
798
+ update_set: name,
799
+ sys_id: sysID,
800
+ state: 'committed',
801
+ commit: { status: progress.label, percent_complete: progress.percent_complete, message: progress.message, tracked: progress.tracked !== false },
802
+ preview_problems: previewProblems.count,
803
+ local_update_set: local,
804
+ }, {
805
+ summary: `Committed retrieved update set "${name}"${local.sys_id ? ` as local update set ${local.sys_id}` : ` (${local.note || 'local update set not confirmed'})`}`,
806
+ });
568
807
  }),
569
808
  })
570
809
  .command({
@@ -789,6 +1028,9 @@ export function updateSetsCmd(wrap) {
789
1028
  console.log(' show <name> Show an update set (type counts + risky items)');
790
1029
  console.log(' export <name> Export an update set to XML (stdout or --out)');
791
1030
  console.log(' import <file> Load retrieved XML (--dry-run inspects locally; --yes confirms)');
1031
+ console.log(' preview <set> Platform preview of a loaded retrieved set; reports problems');
1032
+ console.log(' problems <set> List preview problems (read-only; never resolves them)');
1033
+ console.log(' commit <set> Commit a previewed retrieved set after problems are resolved');
792
1034
  console.log(' reopen <name> Explicitly return a closed set to in progress');
793
1035
  console.log(' set [name] Set the current update set (picker when run bare)');
794
1036
  console.log(' create Create a new update set (auto-sets as current)');
package/src/sdk.js CHANGED
@@ -6,6 +6,11 @@ import { AppError, CodeAPI, CodeAuth, errAuth, errAuthHint, errAPI, errNetwork,
6
6
  import { getStringField } from './helpers.js';
7
7
  import { getAction, getStepTypes, createAction, updateAction, testAction } from './processflow-actions.js';
8
8
  import { readSkippedBaseline, revertSkippedUpdate } from './skipped-update-provider.js';
9
+ import {
10
+ previewUpdateSet as previewRetrievedUpdateSet,
11
+ commitUpdateSet as commitRetrievedUpdateSet,
12
+ listPreviewProblems,
13
+ } from './update-set-apply.js';
9
14
 
10
15
  const DEFAULT_TIMEOUT = 30000;
11
16
 
@@ -834,6 +839,32 @@ export class SDKClient {
834
839
  }
835
840
  }
836
841
 
842
+ /**
843
+ * Preview a loaded retrieved update set through the CICD Update Set API and
844
+ * wait for its progress tracker. Does not commit and does not resolve
845
+ * preview problems.
846
+ * @param {string} sysID - sys_remote_update_set sys_id
847
+ * @param {{timeoutMs?: number, pollMs?: number}} [opts]
848
+ */
849
+ async previewUpdateSet(sysID, opts = {}) {
850
+ return previewRetrievedUpdateSet(this, sysID, opts);
851
+ }
852
+
853
+ /**
854
+ * Commit a previewed retrieved update set through the CICD Update Set API and
855
+ * wait for its progress tracker.
856
+ * @param {string} sysID - sys_remote_update_set sys_id
857
+ * @param {{timeoutMs?: number, pollMs?: number}} [opts]
858
+ */
859
+ async commitUpdateSet(sysID, opts = {}) {
860
+ return commitRetrievedUpdateSet(this, sysID, opts);
861
+ }
862
+
863
+ /** Read sys_update_preview_problem rows for a retrieved update set. */
864
+ async listUpdateSetPreviewProblems(sysID, opts = {}) {
865
+ return listPreviewProblems(this, sysID, opts);
866
+ }
867
+
837
868
  /**
838
869
  * Execute a background script on the ServiceNow instance via sys.scripts.do.
839
870
  * Uses a 3-step session-establishment flow compatible with OAuth tokens:
@@ -0,0 +1,287 @@
1
+ // Preview and commit a *retrieved* update set, and read its preview problems.
2
+ //
3
+ // These are the platform's own steps: retrieving (import) only loads the XML,
4
+ // previewing compares it with the target, and committing applies it. ServiceNow
5
+ // exposes all three through the CICD Update Set API (sn_cicd):
6
+ //
7
+ // POST /api/sn_cicd/update_set/preview/{remote_update_set_id}
8
+ // POST /api/sn_cicd/update_set/commit/{remote_update_set_id}
9
+ // GET /api/sn_cicd/progress/{progress_id}
10
+ //
11
+ // The alternate path — calling hidden Ajax processors or scripting
12
+ // GlideUpdateManager2 from a background script — is deliberately not used: it
13
+ // bypasses the platform's own validation and is not a public contract.
14
+ //
15
+ // Nothing here resolves, ignores, or skips a preview problem. A human decides
16
+ // those in ServiceNow; jsn reports them and refuses to commit while unresolved
17
+ // problems remain.
18
+ import { AppError, CodeAPI, CodeUsage, errUsage } from './errors.js';
19
+
20
+ // sn_cicd progress statuses (same vocabulary as commands/atf.js).
21
+ const PROGRESS_PENDING = '0';
22
+ const PROGRESS_RUNNING = '1';
23
+ const PROGRESS_SUCCESSFUL = '2';
24
+ const PROGRESS_ERROR = '3';
25
+ const PROGRESS_CANCELED = '4';
26
+ const TERMINAL_STATUSES = new Set([PROGRESS_SUCCESSFUL, PROGRESS_ERROR, PROGRESS_CANCELED]);
27
+
28
+ // sys_update_preview_problem.status values that mean a human already decided.
29
+ const RESOLVED_PROBLEM_STATUSES = new Set(['ignored', 'skipped', 'skip_collision', 'accepted', 'resolved']);
30
+
31
+ export const PREVIEW_PROBLEM_TABLE = 'sys_update_preview_problem';
32
+ export const DEFAULT_OPERATION_TIMEOUT_MS = 10 * 60 * 1000;
33
+ const DEFAULT_POLL_MS = 2000;
34
+
35
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
36
+
37
+ function text(value) {
38
+ if (value == null) return '';
39
+ if (typeof value === 'string') return value;
40
+ if (typeof value === 'object') {
41
+ if (value.display_value != null) return String(value.display_value);
42
+ if (value.value != null) return String(value.value);
43
+ }
44
+ return String(value);
45
+ }
46
+
47
+ function statusWord(status) {
48
+ switch (status) {
49
+ case PROGRESS_PENDING: return 'pending';
50
+ case PROGRESS_RUNNING: return 'running';
51
+ case PROGRESS_SUCCESSFUL: return 'successful';
52
+ case PROGRESS_ERROR: return 'failed';
53
+ case PROGRESS_CANCELED: return 'canceled';
54
+ default: return 'unknown';
55
+ }
56
+ }
57
+
58
+ /** Normalize a sn_cicd operation/progress response into one shape. */
59
+ export function normalizeProgress(response) {
60
+ const inner = response?.result && typeof response.result === 'object' ? response.result : (response ?? {});
61
+ const status = inner.status == null ? '' : String(inner.status);
62
+ const percent = Number(inner.percent_complete ?? 0);
63
+ // Live progress bodies carry status_message:"" and put the reason in error.
64
+ // An empty string must not mask the real failure text.
65
+ const message = [inner.status_message, inner.status_detail, inner.error]
66
+ .map((value) => text(value).trim())
67
+ .find((value) => value) || '';
68
+ return {
69
+ status,
70
+ label: String(inner.status_label ?? '') || statusWord(status),
71
+ percent_complete: Number.isFinite(percent) ? percent : 0,
72
+ message,
73
+ progress_id: text(inner?.links?.progress?.id ?? inner.progress_id ?? ''),
74
+ result_id: text(inner?.links?.results?.id ?? inner.result_id ?? ''),
75
+ raw: inner,
76
+ };
77
+ }
78
+
79
+ export function isTerminalProgress(progress) {
80
+ if (TERMINAL_STATUSES.has(progress.status)) return true;
81
+ return /^(successful|success|complete|completed|failed|failure|error|canceled|cancelled)$/i.test(progress.label);
82
+ }
83
+
84
+ export function isSuccessfulProgress(progress) {
85
+ if (progress.status === PROGRESS_SUCCESSFUL) return true;
86
+ return /^(successful|success|complete|completed)$/i.test(progress.label);
87
+ }
88
+
89
+ /**
90
+ * Follow GET /api/sn_cicd/progress/{id} until the operation reaches a terminal
91
+ * status or the deadline passes.
92
+ *
93
+ * A response without a progress link cannot be followed; it is returned as-is
94
+ * so the caller can verify the target's own state instead of guessing.
95
+ *
96
+ * @param {object} sdk - SDK client (request + baseURL)
97
+ * @param {object} initial - dispatch response from the operation endpoint
98
+ * @param {object} [options]
99
+ * @param {number} [options.timeoutMs]
100
+ * @param {number} [options.pollMs]
101
+ * @param {Function} [options.wait] - sleep seam for tests
102
+ * @param {Function} [options.now] - clock seam for tests
103
+ * @param {Function} [options.onProgress] - called with each normalized update
104
+ * @returns {Promise<object>} the last normalized progress
105
+ */
106
+ export async function waitForCicdProgress(sdk, initial, options = {}) {
107
+ const {
108
+ timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS,
109
+ pollMs = DEFAULT_POLL_MS,
110
+ wait = sleep,
111
+ now = Date.now,
112
+ onProgress,
113
+ } = options;
114
+
115
+ let current = normalizeProgress(initial);
116
+ const deadline = now() + timeoutMs;
117
+ let tracked = Boolean(current.progress_id);
118
+
119
+ while (!isTerminalProgress(current)) {
120
+ if (now() >= deadline) {
121
+ throw new AppError(
122
+ CodeAPI,
123
+ `Timed out after ${Math.round(timeoutMs / 1000)}s waiting for the update set operation (last status: ${current.label}).\n` +
124
+ 'The operation may still be running on the instance. Inspect Retrieved Update Sets before retrying; jsn does not repeat it.',
125
+ '',
126
+ 0,
127
+ );
128
+ }
129
+ if (!tracked) return { ...current, tracked };
130
+ await wait(pollMs);
131
+ const response = await sdk.request(`${sdk.baseURL}/api/sn_cicd/progress/${encodeURIComponent(current.progress_id)}`, { method: 'GET' });
132
+ const next = normalizeProgress(response);
133
+ current = {
134
+ ...next,
135
+ progress_id: next.progress_id || current.progress_id,
136
+ result_id: next.result_id || current.result_id,
137
+ };
138
+ tracked = Boolean(current.progress_id);
139
+ if (typeof onProgress === 'function') onProgress(current);
140
+ }
141
+ return { ...current, tracked };
142
+ }
143
+
144
+ function cicdUnavailable(error) {
145
+ if (error?.status === 404) return true;
146
+ if (error?.status === 400 && /Requested URI does not represent any resource/i.test(error.message || '')) return true;
147
+ return false;
148
+ }
149
+
150
+ /**
151
+ * A sn_cicd error body can be an operation result rather than a missing route.
152
+ * Live 404 for an unknown update set:
153
+ * {"result":{"status":"3","status_label":"Failed","error":"Update set with id ... cannot be found"}}
154
+ * That is a rejected operation, not an absent plugin.
155
+ */
156
+ function cicdOperationError(error) {
157
+ const body = error?.message;
158
+ if (typeof body !== 'string') return '';
159
+ // errAPI prefixes the HTTP status, so the JSON envelope may not start the
160
+ // message. Parse from the first brace.
161
+ const start = body.indexOf('{');
162
+ if (start < 0) return '';
163
+ try {
164
+ const result = JSON.parse(body.slice(start))?.result;
165
+ if (result && typeof result === 'object') {
166
+ return text(result.error || result.status_message || result.status_detail).trim();
167
+ }
168
+ } catch { /* not a JSON error envelope */ }
169
+ return '';
170
+ }
171
+
172
+ /**
173
+ * Start a sn_cicd update-set operation and wait for its tracker.
174
+ * @param {object} sdk
175
+ * @param {'preview'|'commit'} operation
176
+ * @param {string} sysID - sys_remote_update_set sys_id
177
+ */
178
+ export async function runUpdateSetOperation(sdk, operation, sysID, options = {}) {
179
+ const endpoint = `${sdk.baseURL}/api/sn_cicd/update_set/${operation}/${encodeURIComponent(sysID)}`;
180
+ let response;
181
+ try {
182
+ response = await sdk.request(endpoint, { method: 'POST', body: '{}' });
183
+ } catch (error) {
184
+ if (error?.status === 403) {
185
+ throw new AppError(
186
+ CodeUsage,
187
+ `This account cannot use the CICD Update Set API; no ${operation} was started.`,
188
+ 'The account needs the sn_cicd.sys_ci_automation role. Preview and commit the set in ServiceNow instead.',
189
+ 403,
190
+ error,
191
+ );
192
+ }
193
+ const platformError = cicdOperationError(error);
194
+ if (platformError) {
195
+ throw new AppError(
196
+ CodeAPI,
197
+ `The CICD API rejected the ${operation}: ${platformError}`,
198
+ `Nothing was ${operation === 'preview' ? 'previewed' : 'committed'}. Inspect the retrieved update set and try again.`,
199
+ error.status || 0,
200
+ error,
201
+ );
202
+ }
203
+ if (cicdUnavailable(error)) {
204
+ throw new AppError(
205
+ CodeUsage,
206
+ `The CICD Update Set API is not available on this instance; no ${operation} was started.`,
207
+ 'The sn_cicd plugin (com.glide.continuousdelivery) provides preview/commit. ' +
208
+ 'Preview and commit the set in ServiceNow instead: System Update Sets > Retrieved Update Sets.',
209
+ error.status || 0,
210
+ error,
211
+ );
212
+ }
213
+ throw error;
214
+ }
215
+
216
+ const final = await waitForCicdProgress(sdk, response, options);
217
+ if (!isSuccessfulProgress(final)) {
218
+ const detail = final.message ? `: ${final.message}` : '';
219
+ throw new AppError(
220
+ CodeAPI,
221
+ `Update set ${operation} did not succeed (${final.label})${detail}`,
222
+ `Inspect Retrieved Update Sets on ${sdk.baseURL} before retrying; jsn does not retry the operation.`,
223
+ 0,
224
+ );
225
+ }
226
+ return final;
227
+ }
228
+
229
+ export async function previewUpdateSet(sdk, sysID, options = {}) {
230
+ return runUpdateSetOperation(sdk, 'preview', sysID, options);
231
+ }
232
+
233
+ export async function commitUpdateSet(sdk, sysID, options = {}) {
234
+ return runUpdateSetOperation(sdk, 'commit', sysID, options);
235
+ }
236
+
237
+ /** Normalize a sys_update_preview_problem row without assuming optional fields. */
238
+ export function normalizePreviewProblem(record) {
239
+ const status = text(record?.status).toLowerCase();
240
+ return {
241
+ sys_id: text(record?.sys_id),
242
+ type: text(record?.type).toLowerCase(),
243
+ description: text(record?.description) || text(record?.problem) || text(record?.message),
244
+ status,
245
+ resolved: RESOLVED_PROBLEM_STATUSES.has(status),
246
+ missing_item: text(record?.missing_item),
247
+ missing_item_table: text(record?.missing_item_table),
248
+ remote_update: text(record?.remote_update_set),
249
+ available_actions: text(record?.available_actions),
250
+ sys_created_on: text(record?.sys_created_on),
251
+ };
252
+ }
253
+
254
+ /**
255
+ * Read the preview problems recorded for a retrieved update set.
256
+ * @returns {Promise<{problems: object[], count: number, unresolved: object[], truncated: boolean}>}
257
+ */
258
+ export async function listPreviewProblems(sdk, sysID, { limit = 500 } = {}) {
259
+ const params = new URLSearchParams();
260
+ params.set('sysparm_query', `remote_update_set=${sysID}^ORDERBYsys_created_on`);
261
+ params.set('sysparm_display_value', 'all');
262
+ params.set('sysparm_limit', String(limit));
263
+ const records = await sdk.listStrict(PREVIEW_PROBLEM_TABLE, params);
264
+ const problems = records.map(normalizePreviewProblem);
265
+ const unresolved = problems.filter((problem) => !problem.resolved);
266
+ return { problems, count: problems.length, unresolved, truncated: problems.length >= limit };
267
+ }
268
+
269
+ /**
270
+ * Refuse to continue while the platform still considers preview problems
271
+ * unresolved. jsn never accepts, skips, or ignores one on the operator's behalf.
272
+ */
273
+ export function assertNoUnresolvedProblems({ problems, unresolved }) {
274
+ if (!unresolved.length) return;
275
+ const lines = unresolved.slice(0, 10).map((problem) => {
276
+ const target = problem.missing_item_table
277
+ ? `${problem.missing_item_table}${problem.missing_item ? `/${problem.missing_item}` : ''}`
278
+ : (problem.remote_update || problem.sys_id);
279
+ return `- ${problem.description || '(no description)'} [${target}]`;
280
+ });
281
+ const more = unresolved.length > lines.length ? `\n… and ${unresolved.length - lines.length} more` : '';
282
+ throw errUsage(
283
+ `Refusing to commit: ${unresolved.length} of ${problems.length} preview problem(s) are unresolved.\n` +
284
+ `${lines.join('\n')}${more}\n` +
285
+ 'Resolve each problem in ServiceNow (Accept or Skip remote update), then rerun preview. jsn does not resolve problems automatically.',
286
+ );
287
+ }