@jacebenson/jsn 5.2.0 → 5.3.0-dev.136.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.
@@ -1,8 +1,11 @@
1
1
  import { parseDataArg, confirmDelete, quoteShellArg } from '../helpers.js';
2
2
  import { errAPI, errUsage } from '../errors.js';
3
+ import { CATALOG_API, readCatalogApiItem, shapeVariables } from './catalog/enrich.js';
3
4
 
4
5
  const ID = /^[a-f0-9]{32}$/i;
5
- const API = '/api/sn_sc/servicecatalog/items';
6
+ const API = CATALOG_API;
7
+ const RITM = '/api/now/table/sc_req_item';
8
+ const MAX_REQUESTED_ITEMS = 10;
6
9
  const object = v => v && typeof v === 'object' && !Array.isArray(v);
7
10
 
8
11
  function emit(app, argv, data, summary, breadcrumbs = []) {
@@ -10,17 +13,67 @@ function emit(app, argv, data, summary, breadcrumbs = []) {
10
13
  app.ok(data, { summary, breadcrumbs: breadcrumbs.map(h => ({ ...h, cmd: h.cmd + connection })) });
11
14
  }
12
15
  function requireId(id) { if (!ID.test(id || '')) throw errUsage('Use the full catalog item sys_id; find it with catalogitems search.'); }
13
- async function describe(app, id) {
14
- requireId(id);
15
- const response = await app.sdk.request(`${app.sdk.baseURL}${API}/${id}`, { method: 'GET' });
16
- if (!object(response?.result) || response.result.sys_id !== id) throw errAPI(200, 'Catalog API returned no readable item with the requested identity.');
17
- return response.result;
16
+
17
+ /**
18
+ * Item definition plus flattened question definitions.
19
+ *
20
+ * This is the request side of the catalog, not a second view command: the
21
+ * questions and the order come from the same payload, so `order` can never
22
+ * disagree with what `catalogitems show` printed. Items the catalog API cannot
23
+ * serve (record producers whose server scripts throw, non-catalog records)
24
+ * fail here rather than submitting against guessed definitions.
25
+ */
26
+ async function inspect(app, id) {
27
+ const item = await readCatalogApiItem(app.sdk, id);
28
+ const variables = shapeVariables(item.variables);
29
+ return { item, variables, variablesReported: Array.isArray(item.variables) };
30
+ }
31
+
32
+ function isAnswered(value) {
33
+ if (value === undefined || value === null) return false;
34
+ if (typeof value === 'string') return value.trim() !== '';
35
+ if (Array.isArray(value)) return value.length > 0;
36
+ return true;
37
+ }
38
+
39
+ /**
40
+ * Compare supplied variables against the item's own question definitions.
41
+ * The server remains the authority; this only refuses an obviously incomplete
42
+ * submission before a confirmation prompt or a POST.
43
+ */
44
+ function reviewVariables(variables, supplied) {
45
+ const required = variables.filter(v => v.mandatory && !v.instance_supplied);
46
+ return {
47
+ requiredVariables: required.map(v => v.name),
48
+ missing: required.filter(v => !isAnswered(supplied[v.name])).map(v => v.name),
49
+ unknown: variables.length ? Object.keys(supplied).filter(name => !variables.some(v => v.name === name)) : [],
50
+ };
18
51
  }
52
+
19
53
  function itemHints(id) {
20
- return [{ action: 'describe', cmd: `jsn catalogitems describe ${id}`, description: 'Inspect catalog inputs and pricing' },
54
+ return [{ action: 'show', cmd: `jsn catalogitems show ${id}`, description: 'Read the item, its questions and required answers' },
21
55
  { action: 'preview', cmd: `jsn catalogitems order ${id} --dry-run --variables-file variables.json`, description: 'Preview an order without submitting' }];
22
56
  }
23
57
 
58
+ /**
59
+ * Read the requested item(s) a submitted order produced. Failure here is
60
+ * reported, never retried, and never turns a placed order into an error.
61
+ */
62
+ async function findRequestedItems(app, requestId) {
63
+ const params = new URLSearchParams({ sysparm_query: `request=${requestId}`, sysparm_fields: 'sys_id,number,cat_item', sysparm_limit: String(MAX_REQUESTED_ITEMS) });
64
+ try {
65
+ const response = await app.sdk.request(`${app.sdk.baseURL}${RITM}?${params}`, { method: 'GET' });
66
+ if (!Array.isArray(response?.result)) return { items: [], readable: false, error: 'unsupported response' };
67
+ return {
68
+ items: response.result.filter(r => object(r) && ID.test(r.sys_id || ''))
69
+ .map(r => ({ sys_id: r.sys_id, number: typeof r.number === 'string' ? r.number : null })),
70
+ readable: true,
71
+ };
72
+ } catch (error) {
73
+ return { items: [], readable: false, error: error?.status ? `HTTP ${error.status}` : 'read failed' };
74
+ }
75
+ }
76
+
24
77
  export function catalogOrderCommands(wrap) {
25
78
  return [
26
79
  { command: 'search <text>', describe: 'Find requestable items through the Service Catalog API',
@@ -35,20 +88,14 @@ export function catalogOrderCommands(wrap) {
35
88
  possibly_truncated: response.result.length === argv.limit }, `${response.result.length} catalog item(s)`,
36
89
  response.result.flatMap(i => itemHints(i.sys_id).slice(0, 1)));
37
90
  }) },
38
- { command: 'describe <id>', aliases: ['inputs'], describe: 'Read requestable item details, pricing and variable definitions',
39
- builder: y => y.positional('id', { type: 'string' }),
40
- handler: wrap(async (argv, app) => {
41
- const item = await describe(app, argv.id);
42
- emit(app, argv, item, item.name || item.short_description || argv.id, itemHints(argv.id));
43
- }) },
44
91
  { command: 'order <id>', describe: 'Submit a catalog order with explicit confirmation',
45
92
  builder: y => y.positional('id', { type: 'string' })
46
93
  .option('variables', { type: 'string', describe: 'JSON object of catalog variable names/values' })
47
94
  .option('variables-file', { type: 'string', describe: 'Read the variables object from a JSON file' })
48
95
  .option('quantity', { type: 'number', default: 1, describe: 'Positive integer quantity (max 1000)' })
49
96
  .option('requested-for', { type: 'string', describe: 'User sys_id; instance delegation rules still apply' })
50
- .option('dry-run', { type: 'boolean', default: false, describe: 'Read item details and preview variable names; no order is submitted' })
51
- .epilogue('Use describe to inspect variables first. Server-side rules validate the order; a preview does not prove submission will succeed. Existing create/list/show commands manage definitions. Orders require a write-enabled profile, including dry runs. No application/update-set selection is needed.'),
97
+ .option('dry-run', { type: 'boolean', default: false, describe: 'Read item details and preview variables; no order is submitted' })
98
+ .epilogue('Use describe to inspect variables and their types first. Requested for is supplied by the instance unless you pass --requested-for, so it is reported separately and never blocks an order. A preview only reads; submitting needs a write-enabled profile and an explicit confirmation (or --force). Server-side rules still validate the order, so a preview does not prove submission will succeed. Existing create/list/show commands manage definitions. Orders need no application/update-set selection.'),
52
99
  handler: wrap(async (argv, app) => {
53
100
  requireId(argv.id);
54
101
  if (!Number.isInteger(argv.quantity) || argv.quantity < 1 || argv.quantity > 1000) throw errUsage('--quantity must be an integer from 1 to 1000.');
@@ -59,12 +106,26 @@ export function catalogOrderCommands(wrap) {
59
106
  const variables = argv.variables !== undefined || file !== undefined
60
107
  ? parseDataArg({ data: argv.variables, 'data-file': file }) : {};
61
108
  if (!object(variables)) throw errUsage('Catalog variables must be a JSON object.');
62
- const item = await describe(app, argv.id);
109
+
110
+ const { item, variables: definitions, variablesReported } = await inspect(app, argv.id);
63
111
  if (item.sys_class_name && item.sys_class_name !== 'sc_cat_item') throw errUsage('order supports standard catalog items; record producers and order guides need their own submission workflows.');
64
112
  if (item.active === false || item.active === 'false' || item.can_order === false) throw errUsage('This item is not currently orderable.');
65
- const plan = { item_id: argv.id, name: item.name || item.short_description, quantity: argv.quantity,
66
- requested_for: requestedFor || null, variable_names: Object.keys(variables) };
113
+
114
+ // Only refuse on local evidence: an unreadable variable list is not
115
+ // proof that an item has no mandatory inputs.
116
+ const review = variablesReported ? reviewVariables(definitions, variables) : null;
117
+ if (review?.missing.length) {
118
+ throw errUsage(`Missing required catalog variable(s): ${review.missing.join(', ')}. Inspect them with: jsn catalogitems describe ${argv.id}`);
119
+ }
120
+
121
+ const plan = {
122
+ item_id: argv.id, name: item.name || item.short_description, quantity: argv.quantity,
123
+ requested_for: requestedFor || null, variable_names: Object.keys(variables),
124
+ required_variables: review ? review.requiredVariables : [],
125
+ ...(review?.unknown.length ? { unknown_variable_names: review.unknown } : {}),
126
+ };
67
127
  if (argv.dryRun ?? argv['dry-run']) return emit(app, argv, { ...plan, submitted: false, server_validation: 'not performed' }, 'Catalog order preview; nothing submitted', itemHints(argv.id));
128
+
68
129
  const rerun = ['catalogitems', 'order', argv.id, '--quantity', String(argv.quantity),
69
130
  ...(requestedFor ? ['--requested-for', requestedFor] : []),
70
131
  ...(file ? ['--variables-file', file] : Object.keys(variables).length ? ['--variables-file', '<variables.json>'] : [])];
@@ -83,11 +144,26 @@ export function catalogOrderCommands(wrap) {
83
144
  throw errAPI(error.status || 0, 'Catalog submission did not return a confirmed order. Inspect your requests before retrying; the order may have been placed.');
84
145
  }
85
146
  const result = response?.result;
86
- const requestId = result?.request_id || result?.sys_id, number = result?.request_number || result?.number;
87
- if (!object(result) || result.error || !ID.test(requestId || '') || typeof number !== 'string' || !number.trim()) throw errAPI(200, 'Catalog response did not confirm an order identity. Inspect your requests before retrying; do not resubmit automatically.');
88
- emit(app, argv, { item_id: argv.id, quantity: argv.quantity, request_id: requestId, request_number: number, submitted: true },
89
- `Ordered: ${number}`, [{ action: 'request', cmd: `jsn records get --table sc_request --sys-id ${requestId}`, description: 'Read the request header' },
90
- { action: 'items', cmd: `jsn requests list --query ${quoteShellArg(`request=${requestId}`)}`, description: 'Track the requested items' }]);
147
+ if (!object(result) || result.error || result.errMsg) throw errAPI(200, 'Catalog response did not confirm an order identity. Inspect your requests before retrying; do not resubmit automatically.');
148
+ // order_now answers with the request header (REQ); the requested item
149
+ // (RITM) identity is only knowable by reading the request's items.
150
+ const requestId = result.request_id || (result.table === 'sc_request' ? result.sys_id : undefined);
151
+ const requestNumber = result.request_number || (result.table === 'sc_request' ? result.number : undefined);
152
+ if (!ID.test(requestId || '') || typeof requestNumber !== 'string' || !requestNumber.trim()) throw errAPI(200, 'Catalog response did not confirm an order identity. Inspect your requests before retrying; do not resubmit automatically.');
153
+
154
+ const requested = await findRequestedItems(app, requestId);
155
+ emit(app, argv, {
156
+ item_id: argv.id, quantity: argv.quantity, request_id: requestId, request_number: requestNumber,
157
+ requested_items: requested.items,
158
+ requested_items_readable: requested.readable,
159
+ ...(requested.error ? { requested_items_error: requested.error } : {}),
160
+ ...(review?.unknown.length ? { unknown_variable_names: review.unknown } : {}),
161
+ submitted: true,
162
+ }, `Ordered: ${requestNumber}`, [
163
+ { action: 'request', cmd: `jsn records get --table sc_request --sys-id ${requestId}`, description: 'Read the request header' },
164
+ ...requested.items.filter(i => i.number).map(i => ({ action: 'item', cmd: `jsn requests show ${i.number}`, description: 'Read the requested item' })),
165
+ { action: 'items', cmd: `jsn requests list --query ${quoteShellArg(`request=${requestId}`)}`, description: 'Track the request\'s items' },
166
+ ]);
91
167
  }) },
92
168
  ];
93
169
  }
@@ -141,8 +141,8 @@ export function catalogCmd(wrap) {
141
141
  })
142
142
  .command({
143
143
  command: 'show <id>',
144
- aliases: ['get'],
145
- describe: 'Show a catalog item',
144
+ aliases: ['get', 'describe', 'inputs'],
145
+ describe: 'Show a catalog item, its questions and required answers',
146
146
  handler: wrap(async (argv, app) => {
147
147
  app.requireInstance();
148
148
  const id = await resolveSysId(app.sdk, { table: 'sc_cat_item', identifier: argv.id, matchField: 'name', resource: 'Catalog item' });
@@ -158,7 +158,7 @@ export function catalogCmd(wrap) {
158
158
  }
159
159
 
160
160
  async function showItem(app, sysID) {
161
- const { data, standalone, setVars, totalVars } = await enrichCatalogItem({
161
+ const { data, variables, totalVars, source } = await enrichCatalogItem({
162
162
  sdk: app.sdk,
163
163
  instanceUrl: app.getEffectiveInstance(),
164
164
  sysID,
@@ -166,15 +166,16 @@ async function showItem(app, sysID) {
166
166
 
167
167
  // Styled-mode rendering (non-enumerable so JSON output stays clean)
168
168
  Object.defineProperty(data, '_formatted', {
169
- value: buildCatalogFormatted(data, standalone, setVars, totalVars),
169
+ value: buildCatalogFormatted(data, variables, source),
170
170
  enumerable: false,
171
171
  configurable: true,
172
172
  });
173
173
 
174
174
  app.ok(data, {
175
- summary: `${data.name} — ${totalVars} variable(s)`,
175
+ summary: `${data.name} — ${totalVars} question(s) from ${source === 'catalog_api' ? 'the catalog API' : 'item_option_new'}`,
176
176
  breadcrumbs: [
177
177
  { action: 'list', cmd: 'jsn catalogitems list', description: 'Back to all catalog items' },
178
+ ...(totalVars ? [{ action: 'order', cmd: `jsn catalogitems order ${sysID} --dry-run`, description: 'Preview an order without submitting' }] : []),
178
179
  ],
179
180
  });
180
181
  }
@@ -1,7 +1,9 @@
1
1
  import { formatCommandList, formatRecordForDisplay, buildQuerySuffix, buildRecordPayload, getStringField, interactiveList, resolveFieldsParam, checkDerivedFields, confirmDelete, verifyWriteBack } from '../helpers.js';
2
2
  import { listRecords, recordListParams, getRecord, createRecord, updateRecord, deleteRecord } from '../records-engine.js';
3
- import { unwrapSysId } from '../resolve-record.js';
3
+ import { resolveRecord, unwrapSysId } from '../resolve-record.js';
4
4
  import { errUsage } from '../errors.js';
5
+ import { AmbClient } from '../amb.js';
6
+ import { watchRecord } from '../record-watch.js';
5
7
  import { declareCapabilities } from '../capabilities.js';
6
8
 
7
9
  declareCapabilities('records', {
@@ -197,6 +199,113 @@ export function recordsCmd(wrap) {
197
199
  });
198
200
  }),
199
201
  })
202
+ .command({
203
+ command: 'watch',
204
+ describe: 'Stream change events for one record through ServiceNow AMB record watchers',
205
+ builder: (y) => y
206
+ .option('table', { type: 'string', demandOption: true, describe: 'Table name' })
207
+ .option('sys-id', { type: 'string', describe: 'Record sys_id' })
208
+ .option('identifier', { type: 'string', describe: 'Identifier value; use --identifier-field number/name/etc for human identifiers' })
209
+ .option('identifier-field', { type: 'string', describe: 'Exact identifier field (default sys_id); disambiguates names and legacy sys_ids' })
210
+ .option('timeout', { type: 'number', default: 0, describe: 'Stop after this many seconds (0 = until interrupted)' })
211
+ .option('max-events', { type: 'number', default: 0, describe: 'Stop after this many change events (0 = unlimited)' })
212
+ .option('state', { type: 'string', choices: ['auto', 'always', 'never'], default: 'auto', describe: 'Fetch current record state after an event: auto (only when the notification lacks detail), always, never' })
213
+ .option('fields', { type: 'string', describe: 'Comma-separated fields for the fetched state (default all readable fields)' })
214
+ .option('reconnect', { type: 'boolean', default: true, describe: 'Reconnect after a dropped connection and report the gap; use --no-reconnect to fail fast' })
215
+ .option('poll-timeout', { type: 'number', default: 60000, describe: 'Long-poll hold timeout in milliseconds (advanced)' })
216
+ .epilogue([
217
+ 'Emits newline-delimited JSON events (type record_change, gap, subscribed, reconnected, watch_summary) with --json or when piped.',
218
+ 'The notification is emitted as the event; a fetched record is attached separately as event.state (source: "fetched").',
219
+ 'Record watchers are best effort: after a reconnect the stream reports a gap and does not replay missed events.',
220
+ 'Requires an interactive ServiceNow session (jsn auth login --browser). Not a durable queue or scheduler.',
221
+ 'Example: jsn records watch --table incident --sys-id <sys_id> --timeout 300 --json',
222
+ 'Example: jsn records watch --table incident --identifier INC0010001 --identifier-field number --max-events 1 --json',
223
+ ].join('\n')),
224
+ handler: wrap(async (argv, app) => {
225
+ const lookup = recordLookup(argv);
226
+ const record = await resolveRecord(app.sdk, { ...lookup, fields: ['sys_id'] });
227
+ const sysID = unwrapSysId(record);
228
+ if (!sysID) throw errUsage('The matched record has no readable sys_id; check field ACLs before retrying.');
229
+ const stateFields = argv.fields ? argv.fields.split(',').filter(Boolean) : null;
230
+
231
+ const controller = new AbortController();
232
+ const cancel = () => controller.abort();
233
+ process.once('SIGINT', cancel);
234
+ process.once('SIGTERM', cancel);
235
+
236
+ const emit = (data, line) => app.output.writeEvent(data, { line });
237
+ // A live record-watcher notification carries `record`: a map of the
238
+ // fields that changed plus sys_* audit fields. It does not carry the
239
+ // `changes` array. Render the changed fields so human output names
240
+ // what moved; the values are current, because the platform does not
241
+ // send the previous value.
242
+ const describeRecord = record => Object.entries(record && typeof record === 'object' ? record : {})
243
+ .filter(([field]) => !field.startsWith('sys_'))
244
+ .slice(0, 5)
245
+ .map(([field, entry]) => {
246
+ const value = entry && typeof entry === 'object' ? (entry.display_value ?? entry.value) : entry;
247
+ return `${field}: ${value === '' || value == null ? '(empty)' : value}`;
248
+ })
249
+ .join(', ');
250
+ const formatEventLine = event => {
251
+ if (event.type === 'record_change') {
252
+ const id = event.display_value || event.sys_id;
253
+ const changes = (event.changes || [])
254
+ .map(c => `${c.field}: ${c.previous_value ?? '?'} → ${c.display_value ?? c.value ?? '?'}`)
255
+ .join(', ');
256
+ const detail = changes || describeRecord(event.record);
257
+ return `${event.received_at} ${event.table} ${id} ${event.operation}${detail ? ` — ${detail}` : ''}`;
258
+ }
259
+ if (event.type === 'unsubscribed') return `unsubscribed${event.reason ? ` (${event.reason})` : ''}`;
260
+ if (event.type === 'gap') return `⚠ connection gap since ${event.since}: ${event.reason} (events in this window were not observed)`;
261
+ if (event.type === 'reconnected') return `⚠ reconnected after ${event.gaps} gap(s); missed events are not replayed`;
262
+ if (event.type === 'watch_summary') {
263
+ return `watch ended (${event.reason}) — ${event.events} event(s), ${event.gaps} gap(s), ${Math.round(event.duration_ms / 1000)}s`;
264
+ }
265
+ if (event.type === 'subscribed') return `watching ${event.channel}`;
266
+ return `${event.type}: ${event.channel || ''}`;
267
+ };
268
+ const onStatus = status => emit(status, formatEventLine(status));
269
+ const onEvent = async event => emit(event, formatEventLine(event));
270
+
271
+ const fetchState = async () => {
272
+ const params = new URLSearchParams({
273
+ sysparm_query: `sys_id=${sysID}`,
274
+ sysparm_limit: '1',
275
+ sysparm_display_value: 'all',
276
+ });
277
+ if (stateFields) params.set('sysparm_fields', [...new Set(['sys_id', ...stateFields])].join(','));
278
+ const rows = await app.sdk.list(argv.table, params);
279
+ return rows[0] ?? null;
280
+ };
281
+
282
+ const client = new AmbClient({
283
+ baseUrl: app.getEffectiveInstance(),
284
+ session: () => app.sdk.ambSession(),
285
+ connectTimeoutMs: argv['poll-timeout'] ?? argv.pollTimeout,
286
+ });
287
+
288
+ try {
289
+ const summary = await watchRecord({
290
+ client,
291
+ table: argv.table,
292
+ sysID,
293
+ timeoutMs: argv.timeout > 0 ? argv.timeout * 1000 : 0,
294
+ maxEvents: argv['max-events'] ?? argv.maxEvents,
295
+ signal: controller.signal,
296
+ statePolicy: argv.state,
297
+ fetchState,
298
+ reconnect: argv.reconnect !== false,
299
+ onStatus,
300
+ onEvent,
301
+ });
302
+ emit(summary, formatEventLine(summary));
303
+ } finally {
304
+ process.removeListener('SIGINT', cancel);
305
+ process.removeListener('SIGTERM', cancel);
306
+ }
307
+ }),
308
+ })
200
309
  .command({
201
310
  command: 'get',
202
311
  describe: 'Get one record by sys_id or an explicit identifier field',