@jacebenson/jsn 5.2.0-dev.131.1 → 5.2.0-dev.133.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 +9 -1
- package/src/commands/store.js +312 -0
- package/src/errors.js +5 -3
- package/src/store.js +588 -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';
|
|
@@ -76,6 +77,7 @@ import { scrapiCmd } from './commands/scrapi.js';
|
|
|
76
77
|
import { b4rulesCmd } from './commands/b4rules.js';
|
|
77
78
|
import { atfCmd } from './commands/atf.js';
|
|
78
79
|
import { scanCmd } from './commands/scan.js';
|
|
80
|
+
import { storeCmd } from './commands/store.js';
|
|
79
81
|
import { approvalsCmd } from './commands/approvals.js';
|
|
80
82
|
import { historyCmd } from './commands/history.js';
|
|
81
83
|
import { perfCmd } from './commands/perf.js';
|
|
@@ -428,6 +430,7 @@ export function buildCLI() {
|
|
|
428
430
|
// DEVELOPER
|
|
429
431
|
.command(atfCmd(wrap))
|
|
430
432
|
.command(scanCmd(wrap))
|
|
433
|
+
.command(storeCmd(wrap))
|
|
431
434
|
.command(approvalsCmd(wrap))
|
|
432
435
|
.command(skippedUpdatesCmd(wrap))
|
|
433
436
|
.command(perfCmd(wrap))
|
|
@@ -583,7 +586,12 @@ export function buildCLI() {
|
|
|
583
586
|
}
|
|
584
587
|
process.exit(0);
|
|
585
588
|
}
|
|
586
|
-
|
|
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');
|
|
587
595
|
process.exit(0);
|
|
588
596
|
}
|
|
589
597
|
// Every other failure here (unknown command, missing required argument,
|
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
import { confirmDelete, quoteShellArg, truncateString } from '../helpers.js';
|
|
2
|
+
import { declareCapabilities } from '../capabilities.js';
|
|
3
|
+
import { AppError, errUsage } from '../errors.js';
|
|
4
|
+
import {
|
|
5
|
+
STORE_TABS, listApplications, showApplication, operationStatus, prepareInstall, prepareUpdate,
|
|
6
|
+
dispatchOperation, waitForOperation, verifyInstalledVersion, boundedLimit, boundedOffset,
|
|
7
|
+
boundedPoll, boundedTimeout,
|
|
8
|
+
} from '../store.js';
|
|
9
|
+
|
|
10
|
+
// Only the lifecycle verbs mutate. search/list/show/status are discovery and
|
|
11
|
+
// inspection: they send no mutation even though the App Client search endpoint
|
|
12
|
+
// is POST-shaped.
|
|
13
|
+
//
|
|
14
|
+
// Install/update are exempt from development capture-context approval for the
|
|
15
|
+
// same reason as catalog ordering: they hand a runtime install request to the
|
|
16
|
+
// App Client, which writes installed-application state rather than capturing
|
|
17
|
+
// metadata into the selected application/update set.
|
|
18
|
+
declareCapabilities('store', {
|
|
19
|
+
mutationSubcommands: ['install', 'update'],
|
|
20
|
+
mutationContextExemptSubcommands: ['install', 'update'],
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
const hint = (action, cmd, description) => ({ action, cmd, description });
|
|
24
|
+
|
|
25
|
+
// Styled views. The generic renderer only prints `data.records` or a flat
|
|
26
|
+
// record, so a store payload (`apps[]` / nested installed+available blocks)
|
|
27
|
+
// rendered as nothing but its summary line. `_formatted` is the documented
|
|
28
|
+
// escape hatch; it is non-enumerable, so --json/--csv are unchanged.
|
|
29
|
+
const cell = (value, width) => truncateString(String(value ?? ''), width).padEnd(width);
|
|
30
|
+
|
|
31
|
+
function attachFormatted(data, text) {
|
|
32
|
+
Object.defineProperty(data, '_formatted', { value: text, enumerable: false, configurable: true });
|
|
33
|
+
return data;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function styledApplications(page) {
|
|
37
|
+
const lines = [
|
|
38
|
+
`${page.count} Store application${page.count === 1 ? '' : 's'} (${page.tab}${page.term ? `, search "${page.term}"` : ''})${page.page_full ? '; page full, more may exist' : ''}`,
|
|
39
|
+
'',
|
|
40
|
+
];
|
|
41
|
+
if (!page.apps.length) {
|
|
42
|
+
lines.push(' (no applications reported for this tab)');
|
|
43
|
+
return lines.join('\n');
|
|
44
|
+
}
|
|
45
|
+
lines.push(`${cell('NAME', 34)} ${cell('SCOPE', 22)} ${cell('INSTALLED', 9)} ${cell('LATEST', 9)} FLAGS`);
|
|
46
|
+
for (const app of page.apps) {
|
|
47
|
+
const blocked = (app.indicators || []).find(item => item.type === 'error');
|
|
48
|
+
const flags = [
|
|
49
|
+
app.installed ? 'installed' : 'not installed',
|
|
50
|
+
app.update_available ? 'update' : '',
|
|
51
|
+
app.blocked ? `blocked${blocked?.message ? `: ${blocked.message}` : ''}` : '',
|
|
52
|
+
].filter(Boolean).join(', ');
|
|
53
|
+
lines.push(`${cell(app.name, 34)} ${cell(app.scope, 22)} ${cell(app.version || '-', 9)} ${cell(app.latest_version || '-', 9)} ${flags}`);
|
|
54
|
+
}
|
|
55
|
+
return lines.join('\n');
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function styledApplication(data) {
|
|
59
|
+
const line = (label, value) => ` ${label.padEnd(12)} ${value}`;
|
|
60
|
+
const lines = [
|
|
61
|
+
`${data.name || data.sys_id}${data.scope ? ` (${data.scope})` : ''}`,
|
|
62
|
+
data.installed ? ` installed ${data.installed.version || 'version unknown'}` : ' not installed on this instance',
|
|
63
|
+
'',
|
|
64
|
+
];
|
|
65
|
+
if (data.installed) {
|
|
66
|
+
lines.push(line('active', data.installed.active === null ? 'unknown' : String(data.installed.active)));
|
|
67
|
+
if (data.installed.install_date) lines.push(line('installed on', data.installed.install_date));
|
|
68
|
+
if (data.installed.update_date) lines.push(line('updated on', data.installed.update_date));
|
|
69
|
+
}
|
|
70
|
+
if (data.available) {
|
|
71
|
+
lines.push(line('latest', data.available.latest_version || 'unknown'));
|
|
72
|
+
lines.push(line('update', data.available.update_available ? 'available' : 'none reported'));
|
|
73
|
+
lines.push(line('versions', data.available.versions?.length ? data.available.versions.join(', ') : 'none reported'));
|
|
74
|
+
if (data.available.compatibilities) lines.push(line('compatible', String(data.available.compatibilities)));
|
|
75
|
+
} else {
|
|
76
|
+
lines.push(line('store data', `unavailable (${data.detail_unavailable || 'no detail returned'})`));
|
|
77
|
+
}
|
|
78
|
+
if (data.entitlement) {
|
|
79
|
+
lines.push(line('installable', data.entitlement.can_install_or_upgrade === null ? 'not reported' : String(data.entitlement.can_install_or_upgrade)));
|
|
80
|
+
if (data.entitlement.price_type) lines.push(line('price', data.entitlement.price_type));
|
|
81
|
+
}
|
|
82
|
+
if (data.blocked) {
|
|
83
|
+
const reasons = (data.indicators || []).map(item => item.message || item.tooltip).filter(Boolean).join('; ');
|
|
84
|
+
lines.push(line('blocked', reasons || 'yes'));
|
|
85
|
+
}
|
|
86
|
+
if (data.dependencies) lines.push(line('depends on', String(data.dependencies)));
|
|
87
|
+
for (const note of data.notes || []) lines.push('', ` note: ${note}`);
|
|
88
|
+
return lines.join('\n');
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function styledTracker(data) {
|
|
92
|
+
const line = (label, value) => ` ${label.padEnd(10)} ${value}`;
|
|
93
|
+
const lines = [
|
|
94
|
+
`Tracker ${data.tracker_id}`,
|
|
95
|
+
line('status', `${data.status_label || data.status || 'unknown'}${data.status ? ` (${data.status})` : ''}`),
|
|
96
|
+
line('progress', data.percent_complete === null ? 'unknown' : `${data.percent_complete}%`),
|
|
97
|
+
];
|
|
98
|
+
if (data.status_message) lines.push(line('message', data.status_message));
|
|
99
|
+
if (data.error) lines.push(line('error', data.error));
|
|
100
|
+
if (data.status_detail) lines.push(line('detail', data.status_detail));
|
|
101
|
+
lines.push(line('finished', data.terminal ? 'yes' : 'no'));
|
|
102
|
+
return lines.join('\n');
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function report(app, argv, data, options) {
|
|
106
|
+
const connection = argv.profile ? ` --profile ${quoteShellArg(argv.profile)}`
|
|
107
|
+
: argv.instance ? ` --instance ${quoteShellArg(argv.instance)}` : '';
|
|
108
|
+
app.ok(data, { ...options, breadcrumbs: (options.breadcrumbs || []).map(item => ({ ...item, cmd: item.cmd + connection })) });
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const tabOption = p => p.option('tab', { type: 'string', default: 'available', choices: Object.keys(STORE_TABS), describe: 'Store tab context' });
|
|
112
|
+
const pageOptions = p => p.option('limit', { type: 'number', default: 20, describe: 'Maximum applications (1–200)' })
|
|
113
|
+
.option('offset', { type: 'number', default: 0, describe: 'Pagination offset' });
|
|
114
|
+
// The positional is NOT named `app`: cli.js attaches the command's App context
|
|
115
|
+
// as argv.app on every command, so a positional called `app` is overwritten
|
|
116
|
+
// before the handler runs and every identifier arrives as the context object.
|
|
117
|
+
const appOption = p => p.positional('application', { type: 'string', describe: 'Application name, scope, or sys_id' });
|
|
118
|
+
const waitOptions = p => p.option('wait', { type: 'boolean', default: false, describe: 'Poll the tracker until it finishes' })
|
|
119
|
+
.option('timeout', { type: 'number', default: 1800, describe: 'Maximum wait in seconds (1–14400); expiry does not cancel the operation' })
|
|
120
|
+
.option('poll-interval', { type: 'number', default: 5, describe: 'Seconds between progress reads (0–300)' })
|
|
121
|
+
.option('dry-run', { type: 'boolean', default: false, describe: 'Resolve and report the intended operation; send nothing' });
|
|
122
|
+
|
|
123
|
+
function appHints(app) {
|
|
124
|
+
const name = app.scope || app.sys_id;
|
|
125
|
+
return [
|
|
126
|
+
hint('show', `jsn store show ${quoteShellArg(name)}`, 'Inspect installed version, available versions, entitlement and dependencies'),
|
|
127
|
+
hint('status', `jsn store status <tracker-id>`, 'Read operation progress after a submission'),
|
|
128
|
+
];
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function listHints(page) {
|
|
132
|
+
const base = page.term ? `jsn store search ${quoteShellArg(page.term)}` : 'jsn store list';
|
|
133
|
+
return [
|
|
134
|
+
...page.apps.slice(0, 5).map(app => hint('show', `jsn store show ${quoteShellArg(app.scope || app.sys_id)}`, `Inspect ${app.name || app.sys_id}`)),
|
|
135
|
+
...(page.page_full ? [hint('next', `${base} --tab ${page.tab} --offset ${page.offset + page.limit} --limit ${page.limit}`, 'Next page')] : []),
|
|
136
|
+
hint('updates', 'jsn store list --tab updates', 'List applications with an available update'),
|
|
137
|
+
];
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function emitList(app, argv, page) {
|
|
141
|
+
report(app, argv, attachFormatted(page, styledApplications(page)), {
|
|
142
|
+
summary: `${page.count} Store application${page.count === 1 ? '' : 's'} (${page.tab}${page.term ? `, search "${page.term}"` : ''})${page.page_full ? '; page full, more may exist' : ''}`,
|
|
143
|
+
breadcrumbs: listHints(page),
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async function runLifecycle(argv, app, operation) {
|
|
148
|
+
const prepare = operation === 'install' ? prepareInstall : prepareUpdate;
|
|
149
|
+
const plan = await prepare(app.sdk, argv.application, operation === 'install'
|
|
150
|
+
? { version: argv.version, demoData: argv.demoData === true }
|
|
151
|
+
: { version: argv.version });
|
|
152
|
+
const publicPlan = {
|
|
153
|
+
operation: plan.operation,
|
|
154
|
+
app: plan.app,
|
|
155
|
+
requested_version: plan.requested_version,
|
|
156
|
+
...(plan.from_version ? { from_version: plan.from_version } : {}),
|
|
157
|
+
...(plan.operation === 'install' ? { demo_data: plan.demo_data } : {}),
|
|
158
|
+
versions: plan.versions,
|
|
159
|
+
installable_checked: plan.installable_checked,
|
|
160
|
+
detail_unavailable: plan.detail_unavailable,
|
|
161
|
+
};
|
|
162
|
+
if (argv.dryRun) {
|
|
163
|
+
report(app, argv, { ...publicPlan, dry_run: true, dispatched: false }, {
|
|
164
|
+
summary: `Would ${operation} ${plan.app.name || plan.app.sys_id} version ${plan.requested_version}; nothing was sent`,
|
|
165
|
+
breadcrumbs: appHints(plan.app),
|
|
166
|
+
});
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
const action = operation === 'install' ? 'Install' : `Update ${plan.app.name || plan.app.sys_id}${plan.from_version ? ` from ${plan.from_version}` : ''} to`;
|
|
170
|
+
await confirmDelete(app, argv, `${action} ServiceNow Store application "${plan.app.name || plan.app.sys_id}" version ${plan.requested_version}?`);
|
|
171
|
+
const started = await dispatchOperation(app.sdk, plan);
|
|
172
|
+
const data = { ...publicPlan, ...started, terminal: false, succeeded: null, verification: null };
|
|
173
|
+
if (!argv.wait) {
|
|
174
|
+
report(app, argv, data, {
|
|
175
|
+
summary: `${operation === 'install' ? 'Installation' : 'Update'} submitted: tracker ${started.tracker_id} — not a completed ${operation === 'install' ? 'installation' : 'update'}`,
|
|
176
|
+
breadcrumbs: [hint('status', `jsn store status ${started.tracker_id}`, 'Poll the tracker'), ...appHints(plan.app)],
|
|
177
|
+
});
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
const timeoutMs = boundedTimeout(argv.timeout) * 1000;
|
|
181
|
+
const pollIntervalMs = boundedPoll(argv.pollInterval) * 1000;
|
|
182
|
+
let progress;
|
|
183
|
+
try {
|
|
184
|
+
progress = await waitForOperation(app.sdk, started.tracker_id, { pollIntervalMs, timeoutMs });
|
|
185
|
+
} catch (error) {
|
|
186
|
+
throw new AppError('store_progress_unavailable',
|
|
187
|
+
`${operation === 'install' ? 'Installation' : 'Update'} ${started.tracker_id} was submitted but progress could not be read: ${error.message}. It may still be running.`,
|
|
188
|
+
`Check jsn store status ${started.tracker_id} before doing anything else; do not resubmit automatically.`);
|
|
189
|
+
}
|
|
190
|
+
Object.assign(data, progress);
|
|
191
|
+
if (data.wait_timed_out) {
|
|
192
|
+
report(app, argv, data, {
|
|
193
|
+
summary: `${operation === 'install' ? 'Installation' : 'Update'} ${started.tracker_id}: still running after ${argv.timeout}s (${data.percent_complete ?? 'unknown'}%); not verified`,
|
|
194
|
+
breadcrumbs: [hint('status', `jsn store status ${started.tracker_id}`, 'Read progress again'), ...appHints(plan.app)],
|
|
195
|
+
});
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
if (!data.succeeded) {
|
|
199
|
+
throw new AppError('store_operation_failed',
|
|
200
|
+
// status_label is the tracker's generic verdict ("Failed"); status_message
|
|
201
|
+
// carries the reason ("Unable to download app package"). Report the reason.
|
|
202
|
+
`${operation === 'install' ? 'Installation' : 'Update'} ${started.tracker_id} failed: ${data.status_message || data.status_label || data.error || 'the tracker reported failure'}.`,
|
|
203
|
+
`Read jsn store status ${started.tracker_id} for progress and the application's upgrade history. The application may be partially installed; do not resubmit automatically.`);
|
|
204
|
+
}
|
|
205
|
+
// Readback can lag the tracker. Reuse the operator's poll interval, capped at
|
|
206
|
+
// the module default, so a fast poll also shortens verification.
|
|
207
|
+
const verification = await verifyInstalledVersion(app.sdk, plan.app, plan.requested_version, {
|
|
208
|
+
intervalMs: pollIntervalMs === 0 ? 0 : Math.min(pollIntervalMs, 2000),
|
|
209
|
+
});
|
|
210
|
+
data.verification = verification;
|
|
211
|
+
if (verification.verified === false) {
|
|
212
|
+
throw new AppError('store_verification_failed',
|
|
213
|
+
`${operation === 'install' ? 'Installation' : 'Update'} ${started.tracker_id} reported success, but sys_store_app reads back version ${verification.installed_version ?? '(none)'} instead of ${plan.requested_version}.`,
|
|
214
|
+
`Inspect the application with jsn store show ${quoteShellArg(plan.app.scope || plan.app.sys_id)} and its upgrade history before retrying; a reported success is not a completed ${operation === 'install' ? 'installation' : 'update'}.`);
|
|
215
|
+
}
|
|
216
|
+
const verifiedText = verification.verified === true
|
|
217
|
+
? `version ${plan.requested_version} verified on sys_store_app`
|
|
218
|
+
: `version not verified (${verification.reason})`;
|
|
219
|
+
report(app, argv, data, {
|
|
220
|
+
summary: `${operation === 'install' ? 'Installed' : 'Updated'} ${plan.app.name || plan.app.sys_id} ${plan.requested_version}; ${verifiedText}`,
|
|
221
|
+
breadcrumbs: [hint('show', `jsn store show ${quoteShellArg(plan.app.scope || plan.app.sys_id)}`, 'Inspect the installed application'), ...appHints(plan.app)],
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
export function storeCmd(wrap) {
|
|
226
|
+
return {
|
|
227
|
+
command: 'store [subcommand]',
|
|
228
|
+
describe: 'Discover ServiceNow Store applications, inspect versions and entitlement, and request explicit installs/updates',
|
|
229
|
+
builder: y => y
|
|
230
|
+
.command({
|
|
231
|
+
command: 'list',
|
|
232
|
+
describe: 'List Store applications for a tab (read-only)',
|
|
233
|
+
builder: p => pageOptions(tabOption(p)),
|
|
234
|
+
handler: wrap(async (argv, app) => {
|
|
235
|
+
const limit = boundedLimit(argv.limit);
|
|
236
|
+
const offset = boundedOffset(argv.offset);
|
|
237
|
+
emitList(app, argv, await listApplications(app.sdk, { tab: argv.tab, limit, offset }));
|
|
238
|
+
}),
|
|
239
|
+
})
|
|
240
|
+
.command({
|
|
241
|
+
command: 'search <term>',
|
|
242
|
+
describe: 'Search Store applications for this instance by term (read-only)',
|
|
243
|
+
builder: p => pageOptions(tabOption(p)).positional('term', { type: 'string', describe: 'Search term' }),
|
|
244
|
+
handler: wrap(async (argv, app) => {
|
|
245
|
+
const term = String(argv.term ?? '').trim();
|
|
246
|
+
if (!term) throw errUsage('Provide a nonempty search term.');
|
|
247
|
+
const limit = boundedLimit(argv.limit);
|
|
248
|
+
const offset = boundedOffset(argv.offset);
|
|
249
|
+
emitList(app, argv, await listApplications(app.sdk, { tab: argv.tab, term, limit, offset }));
|
|
250
|
+
}),
|
|
251
|
+
})
|
|
252
|
+
.command({
|
|
253
|
+
command: 'show <application>',
|
|
254
|
+
describe: 'Inspect installed version, available versions, entitlement, dependencies and compatibility (read-only)',
|
|
255
|
+
builder: appOption,
|
|
256
|
+
handler: wrap(async (argv, app) => {
|
|
257
|
+
const data = await showApplication(app.sdk, argv.application);
|
|
258
|
+
attachFormatted(data, styledApplication(data));
|
|
259
|
+
report(app, argv, data, {
|
|
260
|
+
summary: `Store application: ${data.name || data.sys_id}${data.installed ? ` (installed ${data.installed.version || 'version unknown'})` : ' (not installed)'}`,
|
|
261
|
+
breadcrumbs: [
|
|
262
|
+
hint('show', `jsn store show ${quoteShellArg(data.scope || data.sys_id)}`, 'Inspect this application'),
|
|
263
|
+
...(data.installed
|
|
264
|
+
? [hint('update', `jsn store update ${quoteShellArg(data.scope || data.sys_id)} --version <version> --dry-run`, 'Resolve an exact update without sending it')]
|
|
265
|
+
: [hint('install', `jsn store install ${quoteShellArg(data.scope || data.sys_id)} --version <version> --dry-run`, 'Resolve an exact install without sending it')]),
|
|
266
|
+
hint('list', 'jsn store list --tab updates', 'List applications with an available update'),
|
|
267
|
+
],
|
|
268
|
+
});
|
|
269
|
+
}),
|
|
270
|
+
})
|
|
271
|
+
.command({
|
|
272
|
+
command: 'status <tracker>',
|
|
273
|
+
describe: 'Read asynchronous install/update progress (read-only)',
|
|
274
|
+
builder: p => p.positional('tracker', { type: 'string', describe: 'Tracker sys_id reported by install/update' }),
|
|
275
|
+
handler: wrap(async (argv, app) => {
|
|
276
|
+
const data = await operationStatus(app.sdk, argv.tracker);
|
|
277
|
+
attachFormatted(data, styledTracker(data));
|
|
278
|
+
report(app, argv, data, {
|
|
279
|
+
summary: `Tracker ${data.tracker_id}: ${data.status_label || data.status || 'unknown'}${data.percent_complete === null ? '' : ` ${data.percent_complete}%`}${data.terminal ? '' : ' (running)'}${data.status_message ? ` — ${data.status_message}` : data.error ? ` — ${data.error}` : ''}`,
|
|
280
|
+
breadcrumbs: [
|
|
281
|
+
...(data.terminal ? [] : [hint('status', `jsn store status ${data.tracker_id}`, 'Read progress again')]),
|
|
282
|
+
hint('list', 'jsn store list --tab updates', 'List applications with an available update'),
|
|
283
|
+
],
|
|
284
|
+
});
|
|
285
|
+
}),
|
|
286
|
+
})
|
|
287
|
+
.command({
|
|
288
|
+
command: 'install <application>',
|
|
289
|
+
describe: 'Install an exact Store application version (declared mutation; contract verified, completion unverified)',
|
|
290
|
+
builder: p => waitOptions(appOption(p))
|
|
291
|
+
.option('version', { type: 'string', describe: 'Exact version to install (required)' })
|
|
292
|
+
.option('demo-data', { type: 'boolean', default: false, describe: 'Load demo data during installation' }),
|
|
293
|
+
handler: wrap(async (argv, app) => runLifecycle(argv, app, 'install')),
|
|
294
|
+
})
|
|
295
|
+
.command({
|
|
296
|
+
command: 'update <application>',
|
|
297
|
+
describe: 'Update an installed Store application to an exact version (declared mutation; contract verified, completion unverified)',
|
|
298
|
+
builder: p => waitOptions(appOption(p))
|
|
299
|
+
.option('version', { type: 'string', describe: 'Exact target version; defaults to the reported latest_version' }),
|
|
300
|
+
handler: wrap(async (argv, app) => runLifecycle(argv, app, 'update')),
|
|
301
|
+
}),
|
|
302
|
+
handler: wrap(async (argv, app) => {
|
|
303
|
+
report(app, argv, { commands: ['search', 'list', 'show', 'status', 'install', 'update'] }, {
|
|
304
|
+
summary: 'ServiceNow Store applications',
|
|
305
|
+
breadcrumbs: [hint('list', 'jsn store list --tab installed', 'List installed applications'),
|
|
306
|
+
hint('search', 'jsn store search "<term>"', 'Search applications available to this instance'),
|
|
307
|
+
hint('show', 'jsn store show <app>', 'Inspect one application'),
|
|
308
|
+
hint('status', 'jsn store status <tracker>', 'Read install/update progress')],
|
|
309
|
+
});
|
|
310
|
+
}),
|
|
311
|
+
};
|
|
312
|
+
}
|
package/src/errors.js
CHANGED
|
@@ -270,9 +270,11 @@ export function renderAppError(err, { app = null, argv = null, identifier = '' }
|
|
|
270
270
|
|
|
271
271
|
if (code === CodeNotFound) {
|
|
272
272
|
let text = `Error (${code}): ${err.message}\n`;
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
273
|
+
// A command that knows why the identifier missed says so; the generic line
|
|
274
|
+
// is only the fallback (it used to replace every command-specific hint, and
|
|
275
|
+
// interpolated the subcommand name as if it were the identifier).
|
|
276
|
+
if (err.hint) text += `\nHint: ${err.hint}\n`;
|
|
277
|
+
else if (identifier) text += `\nHint: The identifier "${identifier}" was not found. Check the name or sys_id.\n`;
|
|
276
278
|
return { stream: 'stderr', text, exitCode: 1 };
|
|
277
279
|
}
|
|
278
280
|
|
package/src/store.js
ADDED
|
@@ -0,0 +1,588 @@
|
|
|
1
|
+
// ServiceNow Store application discovery, inspection and explicit lifecycle
|
|
2
|
+
// operations.
|
|
3
|
+
//
|
|
4
|
+
// Wire contract
|
|
5
|
+
// -------------
|
|
6
|
+
// The App Client REST surface used here is the one documented by the App
|
|
7
|
+
// Client application itself (sn_appclient) and implemented by the reference
|
|
8
|
+
// Store CLI named in issue #400 (sonisoft-cnanda/now-sdk-ext-cli):
|
|
9
|
+
//
|
|
10
|
+
// POST /api/sn_appclient/appmanager/apps?tab_context=…&search_key=…
|
|
11
|
+
// &sysparm_limit=…&sysparm_offset=… -> result.apps[]
|
|
12
|
+
// GET /api/sn_appclient/appmanager/app/{app_sys_id} -> result.app_info_on_instance
|
|
13
|
+
// GET /api/sn_appclient/appmanager/app/install?app_id=…&version=…
|
|
14
|
+
// GET /api/sn_appclient/appmanager/app/update?app_id=…&version=…
|
|
15
|
+
// GET /api/sn_cicd/progress/{tracker_id} -> result{status,percent_complete,…}
|
|
16
|
+
//
|
|
17
|
+
// This contract has NOT been verified against a live Store-entitled instance
|
|
18
|
+
// from this repository: there is no such instance in CI and no way to obtain
|
|
19
|
+
// one. Discovery/inspection is implemented and tested against a mock
|
|
20
|
+
// transport; install/update are declared mutations behind the same contract
|
|
21
|
+
// and are labelled unverified in the PR. A maintainer with a Store-entitled
|
|
22
|
+
// instance must confirm the endpoints, the required roles, and the version
|
|
23
|
+
// list shape before treating the mutation path as proven.
|
|
24
|
+
//
|
|
25
|
+
// The search endpoint is POST-shaped (an empty JSON body), but performs no
|
|
26
|
+
// mutation. Read-only profiles may use it; `install`/`update` remain the only
|
|
27
|
+
// declared mutation subcommands.
|
|
28
|
+
|
|
29
|
+
import { AppError, errAPI, errAmbiguous, errNotFoundHint, errUsage, errUsageHint } from './errors.js';
|
|
30
|
+
import { isSysId, unwrapSysId } from './resolve-record.js';
|
|
31
|
+
|
|
32
|
+
/** Store tab contexts, as named by the App Client. */
|
|
33
|
+
export const STORE_TABS = {
|
|
34
|
+
available: 'available_for_you',
|
|
35
|
+
installed: 'installed',
|
|
36
|
+
updates: 'updates',
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
const APPS_PATH = '/api/sn_appclient/appmanager/apps';
|
|
40
|
+
const APP_PATH = '/api/sn_appclient/appmanager/app';
|
|
41
|
+
const INSTALL_PATH = '/api/sn_appclient/appmanager/app/install';
|
|
42
|
+
const UPDATE_PATH = '/api/sn_appclient/appmanager/app/update';
|
|
43
|
+
const PROGRESS_PATH = '/api/sn_cicd/progress';
|
|
44
|
+
|
|
45
|
+
const INSTALLED_FIELDS = 'sys_id,name,scope,version,active,latest_version,install_date,update_date';
|
|
46
|
+
const MAX_VERSION_ATTEMPTS = 6;
|
|
47
|
+
const DEFAULT_VERIFY_INTERVAL_MS = 2000;
|
|
48
|
+
|
|
49
|
+
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
50
|
+
|
|
51
|
+
/** Platform booleans arrive as true/false, 'true'/'false', or 1/0. */
|
|
52
|
+
export const storeFlag = value => value === true || value === 'true' || value === 1 || value === '1';
|
|
53
|
+
|
|
54
|
+
/** Unwrap a raw or display-valued field. */
|
|
55
|
+
export function storeText(record, field) {
|
|
56
|
+
const value = record?.[field];
|
|
57
|
+
if (value === undefined || value === null) return '';
|
|
58
|
+
if (typeof value === 'object') return String(value.value ?? value.display_value ?? '');
|
|
59
|
+
return String(value);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function boundedLimit(value = 20) {
|
|
63
|
+
if (!Number.isInteger(value) || value < 1 || value > 200) throw errUsage('--limit must be an integer from 1 to 200.');
|
|
64
|
+
return value;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function boundedOffset(value = 0) {
|
|
68
|
+
if (!Number.isInteger(value) || value < 0) throw errUsage('--offset must be a nonnegative integer.');
|
|
69
|
+
return value;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function boundedTimeout(value = 1800) {
|
|
73
|
+
if (!Number.isFinite(value) || value < 1 || value > 14400) throw errUsage('--timeout must be from 1 to 14400 seconds.');
|
|
74
|
+
return Math.round(value);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function boundedPoll(value = 5) {
|
|
78
|
+
if (!Number.isFinite(value) || value < 0 || value > 300) throw errUsage('--poll-interval must be from 0 to 300 seconds.');
|
|
79
|
+
return Math.round(value);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function requireIdentifier(value) {
|
|
83
|
+
const text = String(value ?? '').trim();
|
|
84
|
+
if (!text) throw errUsage('Provide a Store application by name, scope, or 32-character sys_id.');
|
|
85
|
+
return text;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* The list endpoint ships `indicators` as a JSON-encoded string; the detail
|
|
90
|
+
* endpoint ships the same entries as a real array. Both carry the platform's
|
|
91
|
+
* own reason an application is unavailable here (for example
|
|
92
|
+
* `not_available_for_instance_type` -> "Unavailable for Instance" on a
|
|
93
|
+
* developer instance), which is the only place that reason appears.
|
|
94
|
+
*/
|
|
95
|
+
export function parseIndicators(value) {
|
|
96
|
+
if (value === undefined || value === null || value === '') return [];
|
|
97
|
+
const raw = typeof value === 'string' ? (() => { try { return JSON.parse(value); } catch { return []; } })() : value;
|
|
98
|
+
if (!Array.isArray(raw)) return [];
|
|
99
|
+
return raw.filter(item => item && typeof item === 'object').map(item => ({
|
|
100
|
+
id: storeText(item, 'id') || null,
|
|
101
|
+
type: storeText(item, 'type') || null,
|
|
102
|
+
message: storeText(item, 'message') || null,
|
|
103
|
+
tooltip: storeText(item, 'tooltip') || null,
|
|
104
|
+
}));
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Reasons the platform gave for blocking an application here. */
|
|
108
|
+
export function blockingIndicators(indicators) {
|
|
109
|
+
return parseIndicators(indicators).filter(item => item.type === 'error');
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* One row from the Store list, reduced to stable, documented fields.
|
|
114
|
+
*
|
|
115
|
+
* The list payload (POST /appmanager/apps) is NOT the detail payload: it has no
|
|
116
|
+
* `isInstalled`, `can_install_or_upgrade`, `is_store_app`, `isAppstorePlugin`,
|
|
117
|
+
* `price_type` or `needs_app_engine_licensing`. The installed marker on a list
|
|
118
|
+
* row is a non-empty `version` (an available row reports `version: null`), and
|
|
119
|
+
* the update marker is `update_available` ("1"). Reading the detail spellings
|
|
120
|
+
* off a list row reported every installed application as not installed.
|
|
121
|
+
*/
|
|
122
|
+
export function summarizeApplication(app) {
|
|
123
|
+
const version = storeText(app, 'version');
|
|
124
|
+
const indicators = parseIndicators(app?.indicators);
|
|
125
|
+
const blockedFlag = app?.block_install === undefined ? null : storeFlag(app.block_install);
|
|
126
|
+
// The list payload always carries `indicators` (an empty array when nothing
|
|
127
|
+
// blocks the app); only a payload without the key leaves the answer unknown.
|
|
128
|
+
const indicatorsReported = app?.indicators !== undefined && app?.indicators !== null;
|
|
129
|
+
return {
|
|
130
|
+
sys_id: storeText(app, 'sys_id'),
|
|
131
|
+
name: storeText(app, 'name'),
|
|
132
|
+
scope: storeText(app, 'scope'),
|
|
133
|
+
vendor: storeText(app, 'vendor'),
|
|
134
|
+
source: storeText(app, 'source'),
|
|
135
|
+
version: version || null,
|
|
136
|
+
latest_version: storeText(app, 'latest_version') || storeText(app, 'latest_version_display') || null,
|
|
137
|
+
installed: storeFlag(app?.isInstalled) || Boolean(version),
|
|
138
|
+
update_available: storeFlag(app?.isInstalledAndUpdateAvailable) || storeFlag(app?.update_available),
|
|
139
|
+
installable: app?.can_install_or_upgrade === undefined ? null : storeFlag(app.can_install_or_upgrade),
|
|
140
|
+
is_store_app: app?.is_store_app === undefined ? null : storeFlag(app.is_store_app),
|
|
141
|
+
is_plugin: app?.isAppstorePlugin === undefined ? null : storeFlag(app.isAppstorePlugin),
|
|
142
|
+
price_type: storeText(app, 'price_type') || null,
|
|
143
|
+
needs_app_engine_licensing: app?.needs_app_engine_licensing === undefined ? null : storeFlag(app.needs_app_engine_licensing),
|
|
144
|
+
blocked: blockedFlag === null && !indicatorsReported ? null : Boolean(blockedFlag) || blockingIndicators(indicators).length > 0,
|
|
145
|
+
indicators,
|
|
146
|
+
short_description: storeText(app, 'short_description') || null,
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* List or search Store applications in one tab context.
|
|
152
|
+
*
|
|
153
|
+
* A 2xx body without `result.apps` is a malformed envelope — an unavailable
|
|
154
|
+
* source, never an empty catalogue.
|
|
155
|
+
*/
|
|
156
|
+
export async function listApplications(sdk, { tab = 'available', term, limit = 20, offset = 0 } = {}) {
|
|
157
|
+
if (!Object.hasOwn(STORE_TABS, tab)) throw errUsage(`--tab must be one of ${Object.keys(STORE_TABS).join(', ')}.`);
|
|
158
|
+
boundedLimit(limit);
|
|
159
|
+
boundedOffset(offset);
|
|
160
|
+
const searchKey = term === undefined || term === null ? '' : String(term).trim();
|
|
161
|
+
const params = new URLSearchParams({
|
|
162
|
+
tab_context: STORE_TABS[tab],
|
|
163
|
+
sysparm_limit: String(limit),
|
|
164
|
+
sysparm_offset: String(offset),
|
|
165
|
+
});
|
|
166
|
+
if (searchKey) params.set('search_key', searchKey);
|
|
167
|
+
const response = await sdk.request(`${sdk.baseURL}${APPS_PATH}?${params}`, { method: 'POST', body: '{}' });
|
|
168
|
+
const apps = response?.result?.apps;
|
|
169
|
+
if (!Array.isArray(apps)) {
|
|
170
|
+
throw new AppError('store_response_malformed',
|
|
171
|
+
'The Store application list returned no apps array. This is an unavailable source, not an empty catalogue.',
|
|
172
|
+
'Confirm this instance exposes the ServiceNow Store App Client API (sn_appclient) and that this account may use it.');
|
|
173
|
+
}
|
|
174
|
+
const rows = apps.filter(Boolean);
|
|
175
|
+
return {
|
|
176
|
+
tab,
|
|
177
|
+
tab_context: STORE_TABS[tab],
|
|
178
|
+
term: searchKey || null,
|
|
179
|
+
count: rows.length,
|
|
180
|
+
limit,
|
|
181
|
+
offset,
|
|
182
|
+
page_full: rows.length === limit,
|
|
183
|
+
apps: rows.map(summarizeApplication),
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Full App Client detail for one app, or null when the client has no record. */
|
|
188
|
+
export async function applicationDetail(sdk, sysId) {
|
|
189
|
+
const response = await sdk.request(`${sdk.baseURL}${APP_PATH}/${encodeURIComponent(sysId)}`, { method: 'GET' });
|
|
190
|
+
const detail = response?.result?.app_info_on_instance;
|
|
191
|
+
return detail && typeof detail === 'object' ? detail : null;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function versionList(detail) {
|
|
195
|
+
const raw = detail?.versions;
|
|
196
|
+
if (!Array.isArray(raw)) return [];
|
|
197
|
+
return raw
|
|
198
|
+
.map(item => (typeof item === 'string' ? item : storeText(item, 'version') || storeText(item, 'version_display') || storeText(item, 'name')))
|
|
199
|
+
.map(item => String(item).trim())
|
|
200
|
+
.filter(Boolean);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function detailName(detail, record, fallback) {
|
|
204
|
+
return storeText(detail, 'name') || storeText(record, 'name') || fallback || '';
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Resolve a human identifier to a Store app sys_id.
|
|
209
|
+
*
|
|
210
|
+
* Order: sys_id, installed/known `sys_store_app` scope, `sys_store_app` name,
|
|
211
|
+
* then the Store search endpoint (exact name or scope only). A company
|
|
212
|
+
* application-repository app is refused explicitly rather than treated as a
|
|
213
|
+
* Store app.
|
|
214
|
+
*/
|
|
215
|
+
export async function resolveApplication(sdk, identifier) {
|
|
216
|
+
const raw = requireIdentifier(identifier);
|
|
217
|
+
if (isSysId(raw)) {
|
|
218
|
+
const sysId = raw.toLowerCase();
|
|
219
|
+
let record = null;
|
|
220
|
+
try {
|
|
221
|
+
record = await sdk.get('sys_store_app', sysId);
|
|
222
|
+
} catch (error) {
|
|
223
|
+
if (error?.status !== 403 && error?.status !== 404) throw error;
|
|
224
|
+
}
|
|
225
|
+
return { sys_id: sysId, record, summary: null, matched_by: 'sys_id' };
|
|
226
|
+
}
|
|
227
|
+
if (/[\^=\n\r]/.test(raw)) {
|
|
228
|
+
throw errUsage('The identifier contains characters reserved by encoded queries; pass the application sys_id instead.');
|
|
229
|
+
}
|
|
230
|
+
for (const field of ['scope', 'name']) {
|
|
231
|
+
const rows = await sdk.listStrict('sys_store_app', {
|
|
232
|
+
sysparm_query: `${field}=${raw}`,
|
|
233
|
+
sysparm_fields: INSTALLED_FIELDS,
|
|
234
|
+
sysparm_limit: '2',
|
|
235
|
+
sysparm_display_value: 'false',
|
|
236
|
+
});
|
|
237
|
+
if (rows.length > 1) {
|
|
238
|
+
throw errAmbiguous('store applications', rows.map(row => `${storeText(row, 'name')} (${storeText(row, 'scope')})`));
|
|
239
|
+
}
|
|
240
|
+
if (rows.length === 1) return { sys_id: unwrapSysId(rows[0]), record: rows[0], summary: null, matched_by: field };
|
|
241
|
+
}
|
|
242
|
+
const found = await listApplications(sdk, { tab: 'available', term: raw, limit: 25, offset: 0 });
|
|
243
|
+
const wanted = raw.toLowerCase();
|
|
244
|
+
const matches = found.apps.filter(app => app.name.toLowerCase() === wanted || app.scope.toLowerCase() === wanted);
|
|
245
|
+
if (matches.length > 1) {
|
|
246
|
+
throw errAmbiguous('store applications', matches.map(app => `${app.name} (${app.scope}) ${app.sys_id}`));
|
|
247
|
+
}
|
|
248
|
+
if (matches.length === 1) return { sys_id: matches[0].sys_id, record: null, summary: matches[0], matched_by: 'store_search' };
|
|
249
|
+
const company = await sdk.list('sys_app', {
|
|
250
|
+
sysparm_query: `scope=${raw}`, sysparm_fields: 'sys_id,name,scope', sysparm_limit: '1',
|
|
251
|
+
}).catch(() => []);
|
|
252
|
+
if (company.length) {
|
|
253
|
+
throw new AppError('store_not_store_app',
|
|
254
|
+
`"${raw}" is not a ServiceNow Store application.`,
|
|
255
|
+
'It matches a company/application-repository application (sys_app). jsn store handles ServiceNow Store applications only; '
|
|
256
|
+
+ 'use `jsn records list --table sys_app` to inspect that one.');
|
|
257
|
+
}
|
|
258
|
+
throw errNotFoundHint('store application', raw,
|
|
259
|
+
`Search the Store for it: jsn store search "${raw}". Only exact name or scope matches are resolved here; pass the sys_id from a search result if several applications share a name.`);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* Inspection view: installed state, available versions, entitlement flags,
|
|
264
|
+
* dependencies and compatibility data where the platform exposes them.
|
|
265
|
+
*/
|
|
266
|
+
export async function showApplication(sdk, identifier) {
|
|
267
|
+
const target = await resolveApplication(sdk, identifier);
|
|
268
|
+
let detail = null;
|
|
269
|
+
let detailUnavailable = null;
|
|
270
|
+
try {
|
|
271
|
+
detail = await applicationDetail(sdk, target.sys_id);
|
|
272
|
+
} catch (error) {
|
|
273
|
+
if (error?.status === 403) detailUnavailable = 'forbidden';
|
|
274
|
+
else if (error?.status === 404) detailUnavailable = 'not_found';
|
|
275
|
+
else throw error;
|
|
276
|
+
}
|
|
277
|
+
if (!detail && !target.record && !target.summary && detailUnavailable) {
|
|
278
|
+
throw errNotFoundHint('store application', identifier,
|
|
279
|
+
'Neither the Store App Client nor the store application table returned this application. Check the identifier and this account\'s Store access.');
|
|
280
|
+
}
|
|
281
|
+
const record = target.record;
|
|
282
|
+
const installedFromDetail = Boolean(detail) && storeFlag(detail.isInstalled);
|
|
283
|
+
const installedFromRecord = !detail && record && storeText(record, 'version') && storeText(record, 'install_date');
|
|
284
|
+
const installed = installedFromDetail || installedFromRecord;
|
|
285
|
+
const installedVersion = storeText(detail, 'version') || (installedFromRecord ? storeText(record, 'version') : '');
|
|
286
|
+
const latestVersion = storeText(detail, 'latest_version') || storeText(detail, 'latest_version_display') || storeText(record, 'latest_version');
|
|
287
|
+
const versions = versionList(detail);
|
|
288
|
+
const indicators = Array.isArray(detail?.indicators) ? detail.indicators : parseIndicators(detail?.indicators);
|
|
289
|
+
const blocked = blockingIndicators(indicators);
|
|
290
|
+
const notes = [];
|
|
291
|
+
if (!detail) {
|
|
292
|
+
notes.push('Store App Client detail is unavailable, so entitlement, dependency and compatibility data could not be read.');
|
|
293
|
+
} else {
|
|
294
|
+
if (detail.can_install_or_upgrade === undefined) notes.push('The Store client did not report whether this application can be installed by this account.');
|
|
295
|
+
else if (!storeFlag(detail.can_install_or_upgrade)) notes.push('The Store client reports this application cannot be installed or upgraded by this account. The platform does not say whether entitlement, licensing, or compatibility is the cause.');
|
|
296
|
+
if (storeFlag(detail.block_install) || blocked.length) {
|
|
297
|
+
const reasons = blocked.map(item => item.message || item.tooltip).filter(Boolean).join('; ');
|
|
298
|
+
notes.push(`The Store client blocks this application on this instance${reasons ? `: ${reasons}` : ' (block_install=true)'}. A blocked application is refused before any install or update request is sent.`);
|
|
299
|
+
}
|
|
300
|
+
if (!versions.length) notes.push('No version list was returned; requested versions cannot be checked locally against the Store catalogue.');
|
|
301
|
+
notes.push('Compatibility and entitlement output is reported exactly as the platform supplies it; jsn does not infer purchase authorization or accept commercial terms.');
|
|
302
|
+
}
|
|
303
|
+
return {
|
|
304
|
+
sys_id: target.sys_id,
|
|
305
|
+
name: detailName(detail, record, target.summary?.name),
|
|
306
|
+
scope: storeText(detail, 'scope') || storeText(record, 'scope') || target.summary?.scope || '',
|
|
307
|
+
vendor: storeText(detail, 'vendor') || target.summary?.vendor || null,
|
|
308
|
+
source: storeText(detail, 'source') || target.summary?.source || null,
|
|
309
|
+
matched_by: target.matched_by,
|
|
310
|
+
is_store_app: detail?.is_store_app === undefined ? target.summary?.is_store_app ?? null : storeFlag(detail.is_store_app),
|
|
311
|
+
is_plugin: detail?.isAppstorePlugin === undefined ? target.summary?.is_plugin ?? null : storeFlag(detail.isAppstorePlugin),
|
|
312
|
+
installed: installed ? {
|
|
313
|
+
version: installedVersion || null,
|
|
314
|
+
active: detail?.active === undefined && record?.active === undefined ? null : storeFlag(detail?.active ?? record?.active),
|
|
315
|
+
install_date: storeText(detail, 'install_date') || storeText(record, 'install_date') || null,
|
|
316
|
+
update_date: storeText(detail, 'update_date') || storeText(record, 'update_date') || null,
|
|
317
|
+
} : null,
|
|
318
|
+
available: detail ? {
|
|
319
|
+
latest_version: latestVersion || null,
|
|
320
|
+
update_available: storeFlag(detail.isInstalledAndUpdateAvailable),
|
|
321
|
+
versions: versions.length ? versions : null,
|
|
322
|
+
compatibilities: detail.compatibilities ?? null,
|
|
323
|
+
} : null,
|
|
324
|
+
entitlement: detail ? {
|
|
325
|
+
can_install_or_upgrade: detail.can_install_or_upgrade === undefined ? null : storeFlag(detail.can_install_or_upgrade),
|
|
326
|
+
can_install_or_upgrade_customization: detail.can_install_or_upgrade_customization === undefined
|
|
327
|
+
? null : storeFlag(detail.can_install_or_upgrade_customization),
|
|
328
|
+
needs_app_engine_licensing: storeFlag(detail.needs_app_engine_licensing),
|
|
329
|
+
price_type: storeText(detail, 'price_type') || null,
|
|
330
|
+
subscription_applicable: storeFlag(detail.isSubscriptionApplicable),
|
|
331
|
+
} : null,
|
|
332
|
+
dependencies: detail?.dependencies ?? null,
|
|
333
|
+
indicators,
|
|
334
|
+
blocked: detail ? Boolean(storeFlag(detail.block_install) || blocked.length) : null,
|
|
335
|
+
customization_available: storeFlag(detail?.isCustomizationUpdateAvailable),
|
|
336
|
+
detail_unavailable: detailUnavailable,
|
|
337
|
+
notes,
|
|
338
|
+
};
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
function assertOfferedVersion(detail, wanted, name) {
|
|
342
|
+
const offered = versionList(detail);
|
|
343
|
+
if (offered.length && !offered.includes(wanted)) {
|
|
344
|
+
throw new AppError('store_version_unavailable',
|
|
345
|
+
`${name || 'This application'} does not offer version ${wanted}.`,
|
|
346
|
+
`Versions the Store reported: ${offered.join(', ')}. Pass one of those with --version.`);
|
|
347
|
+
}
|
|
348
|
+
return offered;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
function assertInstallable(detail, verb, name) {
|
|
352
|
+
if (!detail) return false;
|
|
353
|
+
const blocked = blockingIndicators(detail.indicators);
|
|
354
|
+
if (storeFlag(detail.block_install) || blocked.length) {
|
|
355
|
+
const reasons = blocked.map(item => item.message || item.tooltip).filter(Boolean).join('; ');
|
|
356
|
+
const flag = storeFlag(detail.block_install) ? 'block_install=true' : `indicator ${blocked.map(item => item.id).filter(Boolean).join(', ')}`;
|
|
357
|
+
throw new AppError('store_app_not_installable',
|
|
358
|
+
`The Store client blocks ${verb === 'install' ? 'installing' : 'updating'} ${name || 'this application'} on this instance${reasons ? `: ${reasons}` : '.'}`,
|
|
359
|
+
`Reported flags: ${flag}. This is the platform's own refusal for this instance; `
|
|
360
|
+
+ 'an application can report can_install_or_upgrade=true and still be blocked here '
|
|
361
|
+
+ '(for example not_available_for_instance_type on a developer instance). '
|
|
362
|
+
+ `Run jsn store show ${name || '<application>'} to see the reported indicators, entitlement and compatibility fields.`);
|
|
363
|
+
}
|
|
364
|
+
if (detail.can_install_or_upgrade !== undefined && !storeFlag(detail.can_install_or_upgrade)) {
|
|
365
|
+
throw new AppError('store_app_not_installable',
|
|
366
|
+
`The Store client reports ${name || 'this application'} cannot be ${verb === 'install' ? 'installed' : 'updated'} by this account.`,
|
|
367
|
+
'Reported flags: can_install_or_upgrade=false. '
|
|
368
|
+
+ 'The platform does not distinguish entitlement, licensing and compatibility as the cause, and jsn does not infer authorization to buy an application or accept commercial terms. '
|
|
369
|
+
+ `Run jsn store show ${name || '<application>'} to see the entitlement and compatibility fields before asking a Store administrator.`);
|
|
370
|
+
}
|
|
371
|
+
return true;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
async function resolvedForMutation(sdk, identifier) {
|
|
375
|
+
const target = await resolveApplication(sdk, identifier);
|
|
376
|
+
let detail = null;
|
|
377
|
+
let detailUnavailable = null;
|
|
378
|
+
try {
|
|
379
|
+
detail = await applicationDetail(sdk, target.sys_id);
|
|
380
|
+
} catch (error) {
|
|
381
|
+
if (error?.status === 403) detailUnavailable = 'forbidden';
|
|
382
|
+
else if (error?.status === 404) detailUnavailable = 'not_found';
|
|
383
|
+
else throw error;
|
|
384
|
+
}
|
|
385
|
+
if (!detail && !target.record && !target.summary) {
|
|
386
|
+
throw errNotFoundHint('store application', identifier,
|
|
387
|
+
'Neither the Store App Client nor the store application table returned this application. Search for it first: jsn store search "<term>".');
|
|
388
|
+
}
|
|
389
|
+
return { target, detail, detailUnavailable };
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/** Resolve an exact app and version and describe the intended install. */
|
|
393
|
+
export async function prepareInstall(sdk, identifier, { version, demoData = false } = {}) {
|
|
394
|
+
const { target, detail, detailUnavailable } = await resolvedForMutation(sdk, identifier);
|
|
395
|
+
const wanted = String(version ?? '').trim();
|
|
396
|
+
if (!wanted) {
|
|
397
|
+
throw errUsageHint('Provide the exact version to install with --version.',
|
|
398
|
+
'jsn store show <app> reports the versions the Store returned; jsn never picks one for you.');
|
|
399
|
+
}
|
|
400
|
+
const app = {
|
|
401
|
+
sys_id: target.sys_id,
|
|
402
|
+
name: detailName(detail, target.record, target.summary?.name),
|
|
403
|
+
scope: storeText(detail, 'scope') || storeText(target.record, 'scope') || target.summary?.scope || '',
|
|
404
|
+
vendor: storeText(detail, 'vendor') || target.summary?.vendor || null,
|
|
405
|
+
};
|
|
406
|
+
const installedVersion = storeFlag(detail?.isInstalled)
|
|
407
|
+
? storeText(detail, 'version')
|
|
408
|
+
: (storeText(target.record, 'install_date') ? storeText(target.record, 'version') : '');
|
|
409
|
+
if (storeFlag(detail?.isInstalled) || installedVersion) {
|
|
410
|
+
throw new AppError('store_already_installed',
|
|
411
|
+
`${app.name || app.sys_id} is already installed${installedVersion ? ` at version ${installedVersion}` : ''}.`,
|
|
412
|
+
`Use an explicit update instead: jsn store update ${app.scope || app.sys_id} --version ${wanted}`);
|
|
413
|
+
}
|
|
414
|
+
const versions = assertOfferedVersion(detail, wanted, app.name);
|
|
415
|
+
const installable = assertInstallable(detail, 'install', app.name);
|
|
416
|
+
return {
|
|
417
|
+
operation: 'install',
|
|
418
|
+
app,
|
|
419
|
+
requested_version: wanted,
|
|
420
|
+
demo_data: Boolean(demoData),
|
|
421
|
+
installed_version: null,
|
|
422
|
+
versions: versions.length ? versions : null,
|
|
423
|
+
installable_checked: installable,
|
|
424
|
+
detail_unavailable: detailUnavailable,
|
|
425
|
+
};
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
/** Resolve an installed app and the exact version to update it to. */
|
|
429
|
+
export async function prepareUpdate(sdk, identifier, { version } = {}) {
|
|
430
|
+
const { target, detail, detailUnavailable } = await resolvedForMutation(sdk, identifier);
|
|
431
|
+
const app = {
|
|
432
|
+
sys_id: target.sys_id,
|
|
433
|
+
name: detailName(detail, target.record, target.summary?.name),
|
|
434
|
+
scope: storeText(detail, 'scope') || storeText(target.record, 'scope') || target.summary?.scope || '',
|
|
435
|
+
vendor: storeText(detail, 'vendor') || target.summary?.vendor || null,
|
|
436
|
+
};
|
|
437
|
+
const installedVersion = storeFlag(detail?.isInstalled)
|
|
438
|
+
? storeText(detail, 'version')
|
|
439
|
+
: (storeText(target.record, 'install_date') ? storeText(target.record, 'version') : '');
|
|
440
|
+
if (!storeFlag(detail?.isInstalled) && !installedVersion) {
|
|
441
|
+
throw new AppError('store_not_installed',
|
|
442
|
+
`${app.name || app.sys_id} is not installed on this instance.`,
|
|
443
|
+
`Install an exact version first: jsn store install ${app.scope || app.sys_id} --version <version>`);
|
|
444
|
+
}
|
|
445
|
+
const wanted = String(version ?? '').trim()
|
|
446
|
+
|| storeText(detail, 'latest_version')
|
|
447
|
+
|| storeText(detail, 'latest_version_display')
|
|
448
|
+
|| '';
|
|
449
|
+
const versions = versionList(detail);
|
|
450
|
+
if (!wanted) {
|
|
451
|
+
throw errUsageHint('Provide the exact version to update to with --version.',
|
|
452
|
+
versions.length ? `Versions the Store reported: ${versions.join(', ')}.` : 'The Store returned no latest version or version list to choose from.');
|
|
453
|
+
}
|
|
454
|
+
if (wanted === installedVersion) {
|
|
455
|
+
throw new AppError('store_version_unchanged',
|
|
456
|
+
`${app.name || app.sys_id} is already at version ${wanted}.`,
|
|
457
|
+
`Pick a different target version${versions.length ? `: ${versions.join(', ')}` : ''}.`);
|
|
458
|
+
}
|
|
459
|
+
assertOfferedVersion(detail, wanted, app.name);
|
|
460
|
+
const installable = assertInstallable(detail, 'update', app.name);
|
|
461
|
+
return {
|
|
462
|
+
operation: 'update',
|
|
463
|
+
app,
|
|
464
|
+
requested_version: wanted,
|
|
465
|
+
from_version: installedVersion || null,
|
|
466
|
+
demo_data: false,
|
|
467
|
+
versions: versions.length ? versions : null,
|
|
468
|
+
installable_checked: installable,
|
|
469
|
+
detail_unavailable: detailUnavailable,
|
|
470
|
+
};
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/** Submit the resolved operation and require a usable tracker id back. */
|
|
474
|
+
export async function dispatchOperation(sdk, plan) {
|
|
475
|
+
const path = plan.operation === 'update' ? UPDATE_PATH : INSTALL_PATH;
|
|
476
|
+
const params = new URLSearchParams({ app_id: plan.app.sys_id, version: plan.requested_version });
|
|
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' });
|
|
479
|
+
const result = response?.result;
|
|
480
|
+
if (!result || typeof result !== 'object') {
|
|
481
|
+
throw errAPI(200, `The ${plan.operation} request returned no result, so the application state is unknown. Inspect the application before retrying.`);
|
|
482
|
+
}
|
|
483
|
+
const tracker = result.tracker_id || result.trackerId || result.links?.progress?.id;
|
|
484
|
+
if (!isSysId(String(tracker ?? ''))) {
|
|
485
|
+
throw new AppError('store_tracker_missing',
|
|
486
|
+
`The ${plan.operation} submission was accepted but returned no tracker id. This is not a completed installation.`,
|
|
487
|
+
'Inspect the application and its install/upgrade history before retrying; do not resubmit automatically.');
|
|
488
|
+
}
|
|
489
|
+
return {
|
|
490
|
+
tracker_id: String(tracker),
|
|
491
|
+
submitted_at: new Date().toISOString(),
|
|
492
|
+
provider_message: storeText(result, 'message') || null,
|
|
493
|
+
};
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
/** Read one progress tracker. Terminal is not the same as successful. */
|
|
497
|
+
export async function operationStatus(sdk, trackerId) {
|
|
498
|
+
const id = String(trackerId ?? '').trim();
|
|
499
|
+
if (!isSysId(id)) throw errUsage('Use the full 32-character tracker id reported by jsn store install/update.');
|
|
500
|
+
const response = await sdk.request(`${sdk.baseURL}${PROGRESS_PATH}/${encodeURIComponent(id)}`, { method: 'GET' });
|
|
501
|
+
const result = response?.result;
|
|
502
|
+
if (!result || typeof result !== 'object') {
|
|
503
|
+
throw new AppError('store_progress_unavailable',
|
|
504
|
+
`Progress tracker ${id} returned no result.`,
|
|
505
|
+
'The operation may still be running. Re-read the tracker before starting another operation; jsn never resubmits automatically.');
|
|
506
|
+
}
|
|
507
|
+
const percent = Number(result.percent_complete);
|
|
508
|
+
const status = storeText(result, 'status');
|
|
509
|
+
const error = storeText(result, 'error');
|
|
510
|
+
const label = storeText(result, 'status_label');
|
|
511
|
+
const message = storeText(result, 'status_message');
|
|
512
|
+
// The tracker's own detail line names the operation and the exact app and
|
|
513
|
+
// version it acted on; it is the only place a failed submission says what it
|
|
514
|
+
// tried to do.
|
|
515
|
+
const detail = storeText(result, 'status_detail');
|
|
516
|
+
const terminal = (Number.isFinite(percent) && percent >= 100) || status === '3' || Boolean(error);
|
|
517
|
+
return {
|
|
518
|
+
tracker_id: id,
|
|
519
|
+
status,
|
|
520
|
+
status_label: label || null,
|
|
521
|
+
status_message: message || null,
|
|
522
|
+
status_detail: detail || null,
|
|
523
|
+
percent_complete: Number.isFinite(percent) ? percent : null,
|
|
524
|
+
error: error || null,
|
|
525
|
+
terminal,
|
|
526
|
+
succeeded: terminal && !error && status !== '3',
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/**
|
|
531
|
+
* Poll a tracker until it is terminal or the wait expires.
|
|
532
|
+
*
|
|
533
|
+
* An expired wait means the operation is still on the instance: the result
|
|
534
|
+
* keeps the tracker id and says so, and nothing is cancelled or resubmitted.
|
|
535
|
+
*/
|
|
536
|
+
export async function waitForOperation(sdk, trackerId, {
|
|
537
|
+
pollIntervalMs = 5000, timeoutMs = 1800_000, onProgress, now = Date.now, wait = sleep,
|
|
538
|
+
} = {}) {
|
|
539
|
+
const startedAt = now();
|
|
540
|
+
let progress = await operationStatus(sdk, trackerId);
|
|
541
|
+
onProgress?.(progress);
|
|
542
|
+
while (!progress.terminal && now() - startedAt < timeoutMs) {
|
|
543
|
+
const remaining = timeoutMs - (now() - startedAt);
|
|
544
|
+
await wait(Math.max(0, Math.min(pollIntervalMs, remaining)));
|
|
545
|
+
progress = await operationStatus(sdk, trackerId);
|
|
546
|
+
onProgress?.(progress);
|
|
547
|
+
}
|
|
548
|
+
return { ...progress, wait_timed_out: !progress.terminal };
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
/**
|
|
552
|
+
* Read the installed record back after a reported success. A reported success
|
|
553
|
+
* is not a completed installation until the instance shows the version.
|
|
554
|
+
*
|
|
555
|
+
* verified: true — readback shows the requested version
|
|
556
|
+
* verified: false — readback shows a different version (or no record)
|
|
557
|
+
* verified: null — the record could not be read, so nothing is claimed
|
|
558
|
+
*/
|
|
559
|
+
export async function verifyInstalledVersion(sdk, { sys_id: sysId }, expectedVersion, {
|
|
560
|
+
attempts = MAX_VERSION_ATTEMPTS, intervalMs = DEFAULT_VERIFY_INTERVAL_MS, wait = sleep,
|
|
561
|
+
} = {}) {
|
|
562
|
+
let record = null;
|
|
563
|
+
let readable = false;
|
|
564
|
+
for (let attempt = 0; attempt < attempts; attempt++) {
|
|
565
|
+
try {
|
|
566
|
+
record = await sdk.get('sys_store_app', sysId);
|
|
567
|
+
readable = true;
|
|
568
|
+
} catch (error) {
|
|
569
|
+
if (error?.status !== 403 && error?.status !== 404) throw error;
|
|
570
|
+
readable = false;
|
|
571
|
+
record = null;
|
|
572
|
+
}
|
|
573
|
+
if (readable && record && storeText(record, 'version') === expectedVersion) break;
|
|
574
|
+
if (attempt < attempts - 1 && intervalMs > 0) await wait(intervalMs);
|
|
575
|
+
}
|
|
576
|
+
if (!readable) {
|
|
577
|
+
return { verified: null, expected_version: expectedVersion, installed_version: null, source: 'sys_store_app', reason: 'readback_unavailable' };
|
|
578
|
+
}
|
|
579
|
+
const installed = storeText(record, 'version');
|
|
580
|
+
return {
|
|
581
|
+
verified: Boolean(record) && installed === expectedVersion,
|
|
582
|
+
expected_version: expectedVersion,
|
|
583
|
+
installed_version: installed || null,
|
|
584
|
+
active: record ? storeFlag(record.active) : null,
|
|
585
|
+
source: 'sys_store_app',
|
|
586
|
+
reason: !record ? 'record_missing' : (installed === expectedVersion ? 'version_confirmed' : 'version_mismatch'),
|
|
587
|
+
};
|
|
588
|
+
}
|
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
|
+
}
|