@jacebenson/jsn 5.2.0-dev.132.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 +1 -1
- package/src/cli.js +7 -1
- package/src/commands/updatesets.js +253 -11
- package/src/sdk.js +31 -0
- package/src/update-set-apply.js +287 -0
- package/src/welcome.js +324 -0
package/package.json
CHANGED
package/src/cli.js
CHANGED
|
@@ -10,6 +10,7 @@ import { App } from './app.js';
|
|
|
10
10
|
import { resolveSession, applySession } from './session.js';
|
|
11
11
|
import { renderHelp, renderTips } from './help.js';
|
|
12
12
|
import { isMutationCommand, refreshMutationCommands } from './mutations.js';
|
|
13
|
+
import { maybeShowWelcome } from './welcome.js';
|
|
13
14
|
import { skippedUpdatesCmd } from './commands/skipped-updates.js';
|
|
14
15
|
import { isLocalPreview, noInstanceCommands, dailyCheckSkipCommands, contextHeaderSkipCommands } from './capabilities.js';
|
|
15
16
|
import { guardExit, exitWithError, AppError, CodeUsage } from './errors.js';
|
|
@@ -585,7 +586,12 @@ export function buildCLI() {
|
|
|
585
586
|
}
|
|
586
587
|
process.exit(0);
|
|
587
588
|
}
|
|
588
|
-
|
|
589
|
+
// First-run orientation (issue #387) sits above the unchanged help.
|
|
590
|
+
// maybeShowWelcome decides for itself: human terminal, no machine
|
|
591
|
+
// format, no configured profile, and not shown before.
|
|
592
|
+
const config = loadConfig(formatArgv);
|
|
593
|
+
maybeShowWelcome({ argv: formatArgv, requestedFormat, cfg: config });
|
|
594
|
+
process.stdout.write(renderHelp(config, visibleCommandRegistry(cliInstance.commandRegistry(), config, formatArgv)) + '\n');
|
|
589
595
|
process.exit(0);
|
|
590
596
|
}
|
|
591
597
|
// Every other failure here (unknown command, missing required argument,
|
|
@@ -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 }, {
|
|
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
|
+
}
|
package/src/welcome.js
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
// First-run welcome (issue #387).
|
|
2
|
+
//
|
|
3
|
+
// A brand-new install that runs bare `jsn` gets grouped help, which assumes
|
|
4
|
+
// the reader already knows what to do with it. This adds a short orientation
|
|
5
|
+
// above that help, exactly once, only when a human is reading it.
|
|
6
|
+
//
|
|
7
|
+
// Invariants (see docs/DECISIONS.md):
|
|
8
|
+
// - at most once: a marker file in the XDG config dir records that the note
|
|
9
|
+
// was shown, and it is created exclusively so two racing first runs cannot
|
|
10
|
+
// both print it;
|
|
11
|
+
// - human terminal only: no --json/--quiet/--csv/--markdown/--get, no piped
|
|
12
|
+
// output, no agent/CI environments;
|
|
13
|
+
// - never instead of help: the grouped help below it is unchanged;
|
|
14
|
+
// - never an instance or auth operation: the note only points at local and
|
|
15
|
+
// interactive commands, so it cannot block setup or require credentials;
|
|
16
|
+
// - nothing on this path reaches the network, prompts, or reads an instance;
|
|
17
|
+
// - not shown to an already-configured installation (profiles exist);
|
|
18
|
+
// - plain ASCII at every width, so NO_COLOR, TERM=dumb and narrow terminals
|
|
19
|
+
// all read the same thing.
|
|
20
|
+
|
|
21
|
+
import fs from 'node:fs';
|
|
22
|
+
import os from 'node:os';
|
|
23
|
+
import path from 'node:path';
|
|
24
|
+
import { globalConfigDir } from './config.js';
|
|
25
|
+
import { canPrompt } from './helpers.js';
|
|
26
|
+
import { getVersion } from './commands/version.js';
|
|
27
|
+
|
|
28
|
+
/** Marker file in the XDG config dir. Presence means "already welcomed". */
|
|
29
|
+
export const WELCOME_MARKER = '.welcomed';
|
|
30
|
+
|
|
31
|
+
/** Line budget for the note at 80 columns (issue #387 hard limit). */
|
|
32
|
+
export const WELCOME_MAX_LINES = 12;
|
|
33
|
+
|
|
34
|
+
/** The note never uses more than this many columns, however wide the terminal. */
|
|
35
|
+
const MAX_WIDTH = 80;
|
|
36
|
+
|
|
37
|
+
/** Below this, descriptions and prose get one word per line; commands never split. */
|
|
38
|
+
const MIN_WIDTH = 24;
|
|
39
|
+
|
|
40
|
+
const HUMAN_FORMATS = new Set(['', 'auto', 'styled']);
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* What a first run actually needs next. Every command here exists, is visible
|
|
44
|
+
* to a profile-less install, and works without an instance:
|
|
45
|
+
* - `jsn setup` opens the interactive add-connection wizard (and defaults);
|
|
46
|
+
* - `jsn auth login <instance>` adds one connection without the wizard;
|
|
47
|
+
* - `jsn --help` is the grouped command list this note sits above;
|
|
48
|
+
* - `jsn docs search` queries ServiceNow documentation, not an instance;
|
|
49
|
+
* - `jsn skill install` writes the bundled agent skill from local files.
|
|
50
|
+
*/
|
|
51
|
+
const STEPS = [
|
|
52
|
+
{ command: 'jsn setup', detail: 'first connection + defaults, interactive' },
|
|
53
|
+
{ command: 'jsn auth login <instance>', detail: 'one connection, scriptable, no wizard' },
|
|
54
|
+
{ command: 'jsn --help', detail: 'every command and flag' },
|
|
55
|
+
{ command: 'jsn docs search <query>', detail: 'search ServiceNow documentation' },
|
|
56
|
+
{ command: 'jsn skill install', detail: 'install the jsn skill for your AI agent' },
|
|
57
|
+
];
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Resolve the terminal width this note may use. Absent or nonsense columns
|
|
61
|
+
* fall back to 80, so a non-interactive writer still gets the documented
|
|
62
|
+
* layout.
|
|
63
|
+
*
|
|
64
|
+
* @param {number|undefined} columns
|
|
65
|
+
* @returns {number}
|
|
66
|
+
*/
|
|
67
|
+
function layoutWidth(columns) {
|
|
68
|
+
const numeric = Number(columns);
|
|
69
|
+
if (!Number.isFinite(numeric) || numeric <= 0) return MAX_WIDTH;
|
|
70
|
+
return Math.max(MIN_WIDTH, Math.min(MAX_WIDTH, Math.floor(numeric)));
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Greedy word wrap that never truncates: a word longer than the width is left
|
|
75
|
+
* whole on its own line rather than cut. Command names are passed with
|
|
76
|
+
* `atomic: true` and are never split at all.
|
|
77
|
+
*
|
|
78
|
+
* @param {string} text
|
|
79
|
+
* @param {number} width
|
|
80
|
+
* @param {string} [indent]
|
|
81
|
+
* @returns {string[]}
|
|
82
|
+
*/
|
|
83
|
+
function wrapText(text, width, indent = '') {
|
|
84
|
+
const words = String(text).split(/\s+/).filter(Boolean);
|
|
85
|
+
const lines = [];
|
|
86
|
+
let current = '';
|
|
87
|
+
for (const word of words) {
|
|
88
|
+
if (!current) {
|
|
89
|
+
current = `${indent}${word}`;
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
if (current.length + 1 + word.length <= width) {
|
|
93
|
+
current += ` ${word}`;
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
lines.push(current);
|
|
97
|
+
current = `${indent}${word}`;
|
|
98
|
+
}
|
|
99
|
+
if (current) lines.push(current);
|
|
100
|
+
return lines;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Candidate labels for "where config lives". The first honest label that fits
|
|
105
|
+
* the width wins, so a long XDG path is replaced by the switch that produced
|
|
106
|
+
* it rather than pushed off the screen.
|
|
107
|
+
*
|
|
108
|
+
* @param {object} env
|
|
109
|
+
* @param {string} configDir
|
|
110
|
+
* @returns {string[]}
|
|
111
|
+
*/
|
|
112
|
+
function configLabels(env, configDir) {
|
|
113
|
+
const home = os.homedir();
|
|
114
|
+
const replaceHome = (value) => (home && value.startsWith(`${home}${path.sep}`)
|
|
115
|
+
? `~${value.slice(home.length)}`
|
|
116
|
+
: value);
|
|
117
|
+
const labels = [`Config: ${replaceHome(path.join(configDir, 'config.json'))}`];
|
|
118
|
+
if (env.XDG_CONFIG_HOME) labels.push('Config: $XDG_CONFIG_HOME/servicenow/config.json');
|
|
119
|
+
labels.push('Config: ~/.config/servicenow/config.json');
|
|
120
|
+
return [...new Set(labels)];
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Render the "Next steps" block. A wide terminal gets command and description
|
|
125
|
+
* on one aligned row; a narrow one puts the description underneath, indented,
|
|
126
|
+
* so the command name is always intact.
|
|
127
|
+
*
|
|
128
|
+
* @param {number} width
|
|
129
|
+
* @returns {string[]}
|
|
130
|
+
*/
|
|
131
|
+
function renderSteps(width) {
|
|
132
|
+
const commandWidth = Math.max(...STEPS.map((step) => step.command.length));
|
|
133
|
+
const alignedColumn = 4 + commandWidth + 2;
|
|
134
|
+
const oneLine = STEPS.every((step) => alignedColumn + step.detail.length <= width);
|
|
135
|
+
const lines = [];
|
|
136
|
+
for (const step of STEPS) {
|
|
137
|
+
if (oneLine) {
|
|
138
|
+
lines.push(` ${step.command.padEnd(commandWidth)} ${step.detail}`);
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
lines.push(` ${step.command}`);
|
|
142
|
+
lines.push(...wrapText(step.detail, width, ' '));
|
|
143
|
+
}
|
|
144
|
+
return lines;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* The orientation text. Kept short: it must fit above the grouped help without
|
|
149
|
+
* pushing it off the first screen, and it must stay inside 12 lines at 80
|
|
150
|
+
* columns.
|
|
151
|
+
*
|
|
152
|
+
* Everything shown is derived from local state: the version comes from the
|
|
153
|
+
* installed package.json, the config path from the same resolution the CLI
|
|
154
|
+
* uses, and the update command from the version's release channel. No network.
|
|
155
|
+
*
|
|
156
|
+
* @param {object} [opts]
|
|
157
|
+
* @param {number} [opts.columns] — terminal width (defaults to process.stdout.columns)
|
|
158
|
+
* @param {object} [opts.env] — environment (defaults to process.env)
|
|
159
|
+
* @param {string} [opts.configDir] — config dir the marker lives in
|
|
160
|
+
* @param {string} [opts.version] — installed version (defaults to package.json)
|
|
161
|
+
* @returns {string[]} lines
|
|
162
|
+
*/
|
|
163
|
+
export function welcomeLines({
|
|
164
|
+
columns = process.stdout?.columns,
|
|
165
|
+
env = process.env,
|
|
166
|
+
configDir = globalConfigDir(),
|
|
167
|
+
version = getVersion(),
|
|
168
|
+
} = {}) {
|
|
169
|
+
const width = layoutWidth(columns);
|
|
170
|
+
const labels = configLabels(env, configDir);
|
|
171
|
+
const configLabel = labels.find((label) => label.length <= width)
|
|
172
|
+
|| labels.reduce((shortest, label) => (label.length < shortest.length ? label : shortest));
|
|
173
|
+
const title = version && version !== '0.0.0'
|
|
174
|
+
? `Welcome to jsn ${version} (ServiceNow from your terminal)`
|
|
175
|
+
: 'Welcome to jsn (ServiceNow from your terminal)';
|
|
176
|
+
return [
|
|
177
|
+
...wrapText(title, width),
|
|
178
|
+
...wrapText(configLabel, width),
|
|
179
|
+
'',
|
|
180
|
+
' Next steps',
|
|
181
|
+
...renderSteps(width),
|
|
182
|
+
'',
|
|
183
|
+
...wrapText('Nothing above needs an instance. jsn asks for credentials only when needed.', width),
|
|
184
|
+
...wrapText('Prints once. Hide it with JSN_NO_WELCOME=1. Update with jsn upgrade.', width),
|
|
185
|
+
];
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* The orientation text as a single string (no trailing newline).
|
|
190
|
+
*
|
|
191
|
+
* @param {object} [opts] — same inputs as welcomeLines
|
|
192
|
+
* @returns {string}
|
|
193
|
+
*/
|
|
194
|
+
export function welcomeText(opts = {}) {
|
|
195
|
+
return welcomeLines(opts).join('\n');
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Marker path for a given config dir (injectable for tests).
|
|
200
|
+
*
|
|
201
|
+
* @param {string} [configDir]
|
|
202
|
+
* @returns {string}
|
|
203
|
+
*/
|
|
204
|
+
export function welcomeMarkerPath(configDir = globalConfigDir()) {
|
|
205
|
+
return path.join(configDir, WELCOME_MARKER);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Decide whether this invocation may show the first-run welcome.
|
|
210
|
+
*
|
|
211
|
+
* Pure except for the marker existence check, so callers and tests can pass
|
|
212
|
+
* every input explicitly.
|
|
213
|
+
*
|
|
214
|
+
* `JSN_NO_WELCOME` is honoured only as the literal value `1`; `0`, an empty
|
|
215
|
+
* value and an unset variable all mean "normal first-run behavior".
|
|
216
|
+
*
|
|
217
|
+
* @param {object} [opts]
|
|
218
|
+
* @param {object} [opts.argv] — parsed args (for `--get` and global format flags)
|
|
219
|
+
* @param {string} [opts.requestedFormat] — format resolved from the same argv
|
|
220
|
+
* @param {object} [opts.cfg] — loaded profile config
|
|
221
|
+
* @param {object} [opts.env] — environment (defaults to process.env)
|
|
222
|
+
* @param {string} [opts.configDir] — config dir holding the marker
|
|
223
|
+
* @param {boolean} [opts.interactive] — a human is reachable (defaults to canPrompt())
|
|
224
|
+
* @returns {boolean}
|
|
225
|
+
*/
|
|
226
|
+
export function shouldShowWelcome({
|
|
227
|
+
argv = {},
|
|
228
|
+
requestedFormat = '',
|
|
229
|
+
cfg = {},
|
|
230
|
+
env = process.env,
|
|
231
|
+
configDir = globalConfigDir(),
|
|
232
|
+
interactive = canPrompt(),
|
|
233
|
+
} = {}) {
|
|
234
|
+
if (env.JSN_NO_WELCOME === '1') return false;
|
|
235
|
+
// Machine-readable output and one-shot extraction never get prose.
|
|
236
|
+
if (!HUMAN_FORMATS.has(requestedFormat || '')) return false;
|
|
237
|
+
if (argv && argv.get) return false;
|
|
238
|
+
if (!interactive) return false;
|
|
239
|
+
// An installation that already has a connection is not a first run. Profiles
|
|
240
|
+
// are the durable record of that (an env-provided instance URL is momentary).
|
|
241
|
+
if (cfg && (Object.keys(cfg.profiles || {}).length > 0 || cfg.defaultProfile)) return false;
|
|
242
|
+
try {
|
|
243
|
+
if (fs.existsSync(welcomeMarkerPath(configDir))) return false;
|
|
244
|
+
} catch {
|
|
245
|
+
// Unreadable config dir: showing the note once more is harmless.
|
|
246
|
+
}
|
|
247
|
+
return true;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* Exclusively record that the welcome was shown.
|
|
252
|
+
*
|
|
253
|
+
* Two first runs racing on the same config dir must not both print the note
|
|
254
|
+
* and must never leave a half-written marker, so the marker is created by
|
|
255
|
+
* hard-linking a fully written temp file: `link(2)` fails with EEXIST for every
|
|
256
|
+
* process but the winner, and the marker path only ever points at complete
|
|
257
|
+
* content.
|
|
258
|
+
*
|
|
259
|
+
* @param {string} [configDir]
|
|
260
|
+
* @returns {'claimed'|'taken'|'unwritable'} — 'taken' means another process
|
|
261
|
+
* already recorded (or recorded concurrently) the note.
|
|
262
|
+
*/
|
|
263
|
+
export function claimWelcome(configDir = globalConfigDir()) {
|
|
264
|
+
const marker = welcomeMarkerPath(configDir);
|
|
265
|
+
const temp = `${marker}.${process.pid}.tmp`;
|
|
266
|
+
const stamp = `${new Date().toISOString()} pid=${process.pid}\n`;
|
|
267
|
+
try {
|
|
268
|
+
fs.mkdirSync(configDir, { recursive: true, mode: 0o750 });
|
|
269
|
+
fs.writeFileSync(temp, stamp, { mode: 0o600 });
|
|
270
|
+
} catch {
|
|
271
|
+
// A read-only or missing config dir must not break the command; the note
|
|
272
|
+
// may be shown again on the next run.
|
|
273
|
+
try { fs.unlinkSync(temp); } catch { /* never created */ }
|
|
274
|
+
return 'unwritable';
|
|
275
|
+
}
|
|
276
|
+
try {
|
|
277
|
+
fs.linkSync(temp, marker);
|
|
278
|
+
return 'claimed';
|
|
279
|
+
} catch (err) {
|
|
280
|
+
if (err && err.code === 'EEXIST') return 'taken';
|
|
281
|
+
// Filesystems without hard links: exclusive create is still a single
|
|
282
|
+
// winner, it just cannot guarantee the marker appears complete.
|
|
283
|
+
try {
|
|
284
|
+
fs.writeFileSync(marker, stamp, { flag: 'wx', mode: 0o600 });
|
|
285
|
+
return 'claimed';
|
|
286
|
+
} catch (fallbackError) {
|
|
287
|
+
if (fallbackError && fallbackError.code === 'EEXIST') return 'taken';
|
|
288
|
+
return 'unwritable';
|
|
289
|
+
}
|
|
290
|
+
} finally {
|
|
291
|
+
try { fs.unlinkSync(temp); } catch { /* already gone */ }
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* Boolean form of claimWelcome for callers that only need "did this process
|
|
297
|
+
* record the note".
|
|
298
|
+
*
|
|
299
|
+
* @param {string} [configDir]
|
|
300
|
+
* @returns {boolean}
|
|
301
|
+
*/
|
|
302
|
+
export function markWelcomeSeen(configDir = globalConfigDir()) {
|
|
303
|
+
return claimWelcome(configDir) === 'claimed';
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* Show the welcome (above the caller's own help output) when this is a first
|
|
308
|
+
* run, then record it. Returns the text that was shown, or '' when nothing was.
|
|
309
|
+
*
|
|
310
|
+
* The marker is claimed before anything is printed, so an interrupted run
|
|
311
|
+
* (Ctrl-C) can leave the note unshown but never printed twice.
|
|
312
|
+
*
|
|
313
|
+
* @param {object} [opts] — same inputs as shouldShowWelcome, plus the
|
|
314
|
+
* welcomeText inputs (columns, version)
|
|
315
|
+
* @returns {string}
|
|
316
|
+
*/
|
|
317
|
+
export function maybeShowWelcome(opts = {}) {
|
|
318
|
+
if (!shouldShowWelcome(opts)) return '';
|
|
319
|
+
const configDir = opts.configDir || globalConfigDir();
|
|
320
|
+
if (claimWelcome(configDir) === 'taken') return '';
|
|
321
|
+
const text = welcomeText({ ...opts, configDir });
|
|
322
|
+
process.stdout.write(`${text}\n\n`);
|
|
323
|
+
return text;
|
|
324
|
+
}
|