@jacebenson/jsn 5.2.0-dev.130.1 → 5.2.0-dev.132.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/skills/servicenow/SKILL.md +11 -1
- package/src/amb.js +370 -0
- package/src/cli.js +2 -0
- package/src/commands/records.js +110 -1
- package/src/commands/store.js +312 -0
- package/src/errors.js +10 -3
- package/src/output.js +27 -0
- package/src/record-watch.js +206 -0
- package/src/sdk.js +35 -1
- package/src/store.js +588 -0
|
@@ -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
|
@@ -54,6 +54,11 @@ export function errAuth(msg) {
|
|
|
54
54
|
return new AppError(CodeAuth, msg, 'Run: jsn auth login');
|
|
55
55
|
}
|
|
56
56
|
|
|
57
|
+
/** Authentication failure with domain-specific recovery guidance. */
|
|
58
|
+
export function errAuthHint(msg, hint) {
|
|
59
|
+
return new AppError(CodeAuth, msg, hint);
|
|
60
|
+
}
|
|
61
|
+
|
|
57
62
|
export function errForbidden(msg) {
|
|
58
63
|
return new AppError(CodeForbidden, msg, '', 403);
|
|
59
64
|
}
|
|
@@ -265,9 +270,11 @@ export function renderAppError(err, { app = null, argv = null, identifier = '' }
|
|
|
265
270
|
|
|
266
271
|
if (code === CodeNotFound) {
|
|
267
272
|
let text = `Error (${code}): ${err.message}\n`;
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
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`;
|
|
271
278
|
return { stream: 'stderr', text, exitCode: 1 };
|
|
272
279
|
}
|
|
273
280
|
|
package/src/output.js
CHANGED
|
@@ -186,6 +186,33 @@ export class OutputWriter {
|
|
|
186
186
|
}
|
|
187
187
|
}
|
|
188
188
|
|
|
189
|
+
/**
|
|
190
|
+
* Write one item of an event stream (e.g. `records watch`).
|
|
191
|
+
*
|
|
192
|
+
* A stream cannot use the single-envelope `ok()`, so this method emits one
|
|
193
|
+
* compact JSON object per line — newline-delimited JSON, the shape agents
|
|
194
|
+
* and scripts can consume incrementally without buffering the whole run.
|
|
195
|
+
* Human formats print `opts.line` (domain-formatted by the command) and
|
|
196
|
+
* fall back to the JSON line when the command supplied none.
|
|
197
|
+
*
|
|
198
|
+
* `--get` stays meaningful: the path is resolved against each event, and
|
|
199
|
+
* a path that does not resolve emits `null` rather than aborting the
|
|
200
|
+
* stream mid-observation.
|
|
201
|
+
*/
|
|
202
|
+
writeEvent(data, opts = {}) {
|
|
203
|
+
const format = this.effectiveFormat();
|
|
204
|
+
if (format === FormatStyled || format === FormatMarkdown) {
|
|
205
|
+
this.writer.write(`${opts.line ?? JSON.stringify(data)}\n`);
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
if (this.jqFilter) {
|
|
209
|
+
const value = resolvePath(data, this.jqFilter);
|
|
210
|
+
this.writer.write(`${JSON.stringify(value === undefined ? null : value)}\n`);
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
this.writer.write(`${JSON.stringify(data)}\n`);
|
|
214
|
+
}
|
|
215
|
+
|
|
189
216
|
writeJSON(data, opts) {
|
|
190
217
|
const resp = { ok: true, data, summary: opts.summary || '', breadcrumbs: opts.breadcrumbs || [] };
|
|
191
218
|
if (opts.notice) resp.notice = opts.notice;
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
// Record watching: bounded observation of one ServiceNow record over AMB.
|
|
2
|
+
//
|
|
3
|
+
// The AMB client (src/amb.js) owns the wire protocol. This module owns the
|
|
4
|
+
// observation session: what counts as an event, when to fetch the record to
|
|
5
|
+
// fill in detail the notification omitted, bounded duration, cancellation,
|
|
6
|
+
// reconnect backoff and — most importantly — honest gap reporting.
|
|
7
|
+
//
|
|
8
|
+
// A record-watcher subscription is best-effort delivery, not a durable
|
|
9
|
+
// stream. After a disconnect the platform does not replay what was missed,
|
|
10
|
+
// so this module reports a gap instead of pretending the event list is
|
|
11
|
+
// complete.
|
|
12
|
+
|
|
13
|
+
import { AppError, CodeUsage } from './errors.js';
|
|
14
|
+
import { normalizeRecordWatcherEvent, recordWatcherChannel } from './amb.js';
|
|
15
|
+
|
|
16
|
+
export const DEFAULT_RECONNECT_DELAYS = [1000, 2000, 4000, 8000, 16000, 30000];
|
|
17
|
+
|
|
18
|
+
function defaultSleep(ms, signal) {
|
|
19
|
+
return new Promise((resolve) => {
|
|
20
|
+
if (signal?.aborted) return resolve();
|
|
21
|
+
const timer = setTimeout(done, ms);
|
|
22
|
+
function done() {
|
|
23
|
+
clearTimeout(timer);
|
|
24
|
+
signal?.removeEventListener('abort', done);
|
|
25
|
+
resolve();
|
|
26
|
+
}
|
|
27
|
+
if (signal) signal.addEventListener('abort', done, { once: true });
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Does the notification carry enough detail that a follow-up read is redundant? */
|
|
32
|
+
export function notificationHasDetail(event) {
|
|
33
|
+
return Boolean(event?.record) || (Array.isArray(event?.changes) && event.changes.length > 0);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Watch one record until a bound is reached, the caller cancels, or a fatal
|
|
38
|
+
* error occurs.
|
|
39
|
+
*
|
|
40
|
+
* @param {object} opts
|
|
41
|
+
* @param {{ start: Function, next: Function, stop: Function }} opts.client
|
|
42
|
+
* @param {string} opts.table
|
|
43
|
+
* @param {string} opts.sysID
|
|
44
|
+
* @param {string} [opts.query] — encoded query; defaults to `sys_id=<sysID>`
|
|
45
|
+
* @param {number} [opts.timeoutMs] — 0 means "until cancelled"
|
|
46
|
+
* @param {number} [opts.maxEvents] — 0 means unlimited
|
|
47
|
+
* @param {AbortSignal} [opts.signal]
|
|
48
|
+
* @param {'auto'|'always'|'never'} [opts.statePolicy]
|
|
49
|
+
* @param {() => Promise<object|null>} [opts.fetchState]
|
|
50
|
+
* @param {(event: object) => any} [opts.onEvent]
|
|
51
|
+
* @param {(status: object) => any} [opts.onStatus]
|
|
52
|
+
* @param {boolean} [opts.reconnect]
|
|
53
|
+
* @param {number[]} [opts.reconnectDelays]
|
|
54
|
+
* @param {() => number} [opts.now]
|
|
55
|
+
* @param {Function} [opts.sleep]
|
|
56
|
+
*/
|
|
57
|
+
export async function watchRecord({
|
|
58
|
+
client,
|
|
59
|
+
table,
|
|
60
|
+
sysID,
|
|
61
|
+
query,
|
|
62
|
+
timeoutMs = 0,
|
|
63
|
+
maxEvents = 0,
|
|
64
|
+
signal,
|
|
65
|
+
statePolicy = 'auto',
|
|
66
|
+
fetchState,
|
|
67
|
+
onEvent = () => {},
|
|
68
|
+
onStatus = () => {},
|
|
69
|
+
reconnect = true,
|
|
70
|
+
reconnectDelays = DEFAULT_RECONNECT_DELAYS,
|
|
71
|
+
now = () => Date.now(),
|
|
72
|
+
sleep = defaultSleep,
|
|
73
|
+
}) {
|
|
74
|
+
if (!client) throw new AppError(CodeUsage, 'Record watch needs an AMB client.');
|
|
75
|
+
if (!table) throw new AppError(CodeUsage, 'Record watch needs a table.');
|
|
76
|
+
if (!sysID) throw new AppError(CodeUsage, 'Record watch needs a record sys_id.');
|
|
77
|
+
if (!['auto', 'always', 'never'].includes(statePolicy)) {
|
|
78
|
+
throw new AppError(CodeUsage, `Unknown state policy: ${statePolicy}`);
|
|
79
|
+
}
|
|
80
|
+
if (timeoutMs < 0 || maxEvents < 0) throw new AppError(CodeUsage, 'Watch bounds cannot be negative.');
|
|
81
|
+
if (statePolicy !== 'never' && typeof fetchState !== 'function') {
|
|
82
|
+
throw new AppError(CodeUsage, 'State fetching is enabled but no record reader was supplied.');
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const channel = recordWatcherChannel(table, query || `sys_id=${sysID}`);
|
|
86
|
+
const startedAt = now();
|
|
87
|
+
const startedISO = new Date(startedAt).toISOString();
|
|
88
|
+
const deadline = timeoutMs > 0 ? startedAt + timeoutMs : Infinity;
|
|
89
|
+
|
|
90
|
+
let events = 0;
|
|
91
|
+
let gaps = 0;
|
|
92
|
+
let attempts = 0;
|
|
93
|
+
let lastEventAt = null;
|
|
94
|
+
let connected = false;
|
|
95
|
+
let reason = 'timeout';
|
|
96
|
+
|
|
97
|
+
const finish = async (why) => {
|
|
98
|
+
reason = why;
|
|
99
|
+
try { await client.stop([channel]); } catch { /* unsubscription is best effort */ }
|
|
100
|
+
onStatus({ type: 'unsubscribed', reason: why });
|
|
101
|
+
const endedAt = now();
|
|
102
|
+
return {
|
|
103
|
+
type: 'watch_summary',
|
|
104
|
+
table,
|
|
105
|
+
sys_id: sysID,
|
|
106
|
+
channel,
|
|
107
|
+
reason: why,
|
|
108
|
+
events,
|
|
109
|
+
gaps,
|
|
110
|
+
reconnects: Math.max(0, gaps),
|
|
111
|
+
complete: gaps === 0 && reason !== 'error',
|
|
112
|
+
started_at: startedISO,
|
|
113
|
+
ended_at: new Date(endedAt).toISOString(),
|
|
114
|
+
duration_ms: Math.max(0, endedAt - startedAt),
|
|
115
|
+
last_event_at: lastEventAt,
|
|
116
|
+
};
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
onStatus({ type: 'connecting', table, sys_id: sysID, channel });
|
|
120
|
+
|
|
121
|
+
try {
|
|
122
|
+
while (true) {
|
|
123
|
+
const remaining = deadline - now();
|
|
124
|
+
if (remaining <= 0) return await finish('timeout');
|
|
125
|
+
if (signal?.aborted) return await finish('cancelled');
|
|
126
|
+
|
|
127
|
+
if (!connected) {
|
|
128
|
+
const session = await client.start([channel]);
|
|
129
|
+
connected = true;
|
|
130
|
+
attempts = 0;
|
|
131
|
+
const resumed = gaps > 0;
|
|
132
|
+
onStatus({
|
|
133
|
+
type: resumed ? 'reconnected' : 'subscribed',
|
|
134
|
+
channel,
|
|
135
|
+
...(session?.sessionStatus ? { session_status: session.sessionStatus } : {}),
|
|
136
|
+
// State the limitation, do not imply the stream was continuous.
|
|
137
|
+
...(resumed ? { may_have_missed_events: true, gaps } : {}),
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
let messages;
|
|
142
|
+
try {
|
|
143
|
+
messages = await client.next({ timeoutMs: Math.min(remaining, 60000), signal });
|
|
144
|
+
} catch (error) {
|
|
145
|
+
if (signal?.aborted) return await finish('cancelled');
|
|
146
|
+
if (deadline - now() <= 0) return await finish('timeout');
|
|
147
|
+
if (error?.fatal === true || !reconnect) throw error;
|
|
148
|
+
|
|
149
|
+
// A dropped connection is a real gap in observation, not a retry note.
|
|
150
|
+
gaps += 1;
|
|
151
|
+
const gapStart = lastEventAt || startedISO;
|
|
152
|
+
const gapAt = new Date(now()).toISOString();
|
|
153
|
+
onStatus({
|
|
154
|
+
type: 'gap',
|
|
155
|
+
at: gapAt,
|
|
156
|
+
since: gapStart,
|
|
157
|
+
reason: error?.message || String(error),
|
|
158
|
+
code: error?.code || null,
|
|
159
|
+
});
|
|
160
|
+
connected = false;
|
|
161
|
+
const wait = reconnectDelays[Math.min(attempts, reconnectDelays.length - 1)];
|
|
162
|
+
attempts += 1;
|
|
163
|
+
const waitedUntil = now() + wait;
|
|
164
|
+
while (now() < waitedUntil && !signal?.aborted && now() < deadline) {
|
|
165
|
+
await sleep(Math.min(wait, Math.max(1, waitedUntil - now())), signal);
|
|
166
|
+
}
|
|
167
|
+
continue;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
for (const message of messages) {
|
|
171
|
+
if (signal?.aborted) return await finish('cancelled');
|
|
172
|
+
const event = normalizeRecordWatcherEvent(message, { table, sysID }, new Date(now()).toISOString());
|
|
173
|
+
// The channel query scopes delivery to this record. The live payload
|
|
174
|
+
// does not carry a sys_id (jsn fills it from the subscription), so this
|
|
175
|
+
// guard only bites on an instance that does send one — for example a
|
|
176
|
+
// table-level channel returning a different record.
|
|
177
|
+
if (event.sys_id && sysID && event.sys_id !== sysID) continue;
|
|
178
|
+
|
|
179
|
+
const shouldFetch = statePolicy === 'always'
|
|
180
|
+
|| (statePolicy === 'auto' && !notificationHasDetail(event));
|
|
181
|
+
if (shouldFetch) {
|
|
182
|
+
try {
|
|
183
|
+
const record = await fetchState();
|
|
184
|
+
event.state = { source: 'fetched', fetched_at: new Date(now()).toISOString(), record };
|
|
185
|
+
} catch (error) {
|
|
186
|
+
// Never let a failed follow-up read masquerade as a failed or
|
|
187
|
+
// complete event; keep the notification and record the problem.
|
|
188
|
+
event.state = null;
|
|
189
|
+
event.state_error = {
|
|
190
|
+
code: error?.code || null,
|
|
191
|
+
message: error?.message || String(error),
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
events += 1;
|
|
197
|
+
lastEventAt = event.received_at;
|
|
198
|
+
await onEvent(event);
|
|
199
|
+
if (maxEvents > 0 && events >= maxEvents) return await finish('max_events');
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
} catch (error) {
|
|
203
|
+
await finish('error');
|
|
204
|
+
throw error;
|
|
205
|
+
}
|
|
206
|
+
}
|
package/src/sdk.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
import { batchRead } from './sdk-batch.js';
|
|
4
4
|
import { gunzipSync } from 'node:zlib';
|
|
5
|
-
import { AppError, CodeAPI, CodeAuth, errAuth, errAPI, errNetwork, errUsage } from './errors.js';
|
|
5
|
+
import { AppError, CodeAPI, CodeAuth, errAuth, errAuthHint, errAPI, errNetwork, errUsage } from './errors.js';
|
|
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';
|
|
@@ -974,6 +974,40 @@ export class SDKClient {
|
|
|
974
974
|
return variables;
|
|
975
975
|
}
|
|
976
976
|
|
|
977
|
+
/**
|
|
978
|
+
* Session material for channels that authorize like a browser (AMB).
|
|
979
|
+
*
|
|
980
|
+
* AMB does not accept bearer/basic headers on subscribe; it needs the
|
|
981
|
+
* cookies and X-UserToken of a UI session. gck credentials already carry
|
|
982
|
+
* them; basic/oauth profiles obtain them by warming the same session the
|
|
983
|
+
* SDK uses for UI calls. A bearer-token profile that cannot warm a session
|
|
984
|
+
* is an actionable error, never a silent fallback.
|
|
985
|
+
*/
|
|
986
|
+
async ambSession() {
|
|
987
|
+
if (!this.authProvider) throw errAuth('No authentication configured');
|
|
988
|
+
const creds = await this.authProvider.getCredentials();
|
|
989
|
+
if (!creds) throw errAuth('No valid credentials');
|
|
990
|
+
if (creds.auth_method === 'gck') {
|
|
991
|
+
if (!creds.cookies) {
|
|
992
|
+
throw errAuthHint('This gck credential has no session cookies, so AMB cannot open a channel.',
|
|
993
|
+
'Re-import the browser session: jsn auth login --browser');
|
|
994
|
+
}
|
|
995
|
+
return { cookies: creds.cookies, userToken: creds.access_token || '', authMethod: 'gck' };
|
|
996
|
+
}
|
|
997
|
+
if (creds.auth_method === 'basic' || creds.auth_method === 'token' || creds.auth_method === 'oauth') {
|
|
998
|
+
const cookies = await this._warmSession();
|
|
999
|
+
if (!cookies) {
|
|
1000
|
+
throw errAuthHint(
|
|
1001
|
+
`${creds.auth_method} credentials could not open a UI session, which AMB requires.`,
|
|
1002
|
+
'Record watching needs a browser session. Run "jsn auth login --browser" and use that profile, or ask an administrator whether AMB is enabled for this account.',
|
|
1003
|
+
);
|
|
1004
|
+
}
|
|
1005
|
+
return { cookies, userToken: this.sessionUserToken || '', authMethod: creds.auth_method };
|
|
1006
|
+
}
|
|
1007
|
+
throw errAuthHint(`Authentication method "${creds.auth_method}" cannot open an AMB session.`,
|
|
1008
|
+
'Use a browser-session (gck) profile: jsn auth login --browser');
|
|
1009
|
+
}
|
|
1010
|
+
|
|
977
1011
|
async _warmSession() {
|
|
978
1012
|
if (this.oauthCookies) return this.oauthCookies;
|
|
979
1013
|
if (!this._sessionPromise) {
|