@jacebenson/jsn 5.1.1 → 5.2.0-dev.130.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/README.md CHANGED
@@ -163,19 +163,82 @@ mapping variable names to values, then preview with
163
163
  Omit `--dry-run` to submit after confirmation. `--quantity` defaults to one;
164
164
  `--requested-for` accepts a user sys_id subject to instance delegation rules.
165
165
 
166
+ `show` is the one view of an item — `describe` and `inputs` are aliases for it.
167
+ It reads the item twice and answers once: the Table API gives the definition
168
+ (`sc_cat_item` plus `item_option_new`), and
169
+ `/api/sn_sc/servicecatalog/items/{id}` gives what this account can actually
170
+ request. The catalog API wins when it answers; the definition list keeps the
171
+ command working when it does not, with `variables_source` naming which one
172
+ answered and `variables_api_error` carrying the reason for the fallback.
173
+
174
+ Questions come back as `{name, label, type, friendly_type, mandatory,
175
+ instance_supplied}` with `required_variables` and `instance_supplied_variables`,
176
+ so a script can build the payload without guessing names or types. Layout
177
+ entries that draw the form but hold no value — containers, labels, HTML and rich
178
+ text blocks, breaks and UI macros — are not reported as questions; only their
179
+ container children are walked. `required_variables` excludes the
180
+ instance-supplied ones: "Requested for" (type 31) is mandatory in the API
181
+ payload, but the instance fills it from the session and `--requested-for`
182
+ overrides it. `order` refuses locally when a required question is missing and an
183
+ unknown variable name is reported as `unknown_variable_names` without blocking.
184
+ The server remains the authority.
185
+
186
+ What the API returns is what a caller can send: questions withheld by a catalog UI
187
+ policy are absent, and a policy-applied mandatory flag is not visible here, so the
188
+ server still decides at submission. Record producers and order guides expose their
189
+ variables but are not orderable through `order`.
190
+
166
191
  Orders use `order_now`, preserving catalog fulfillment rather than inserting an
167
- RITM directly. The command handles standard catalog items; record producers and
168
- order guides require separate workflows. Server rules validate mandatory and
169
- dynamic variables at submission; a preview does not validate those rules. Preview
170
- output lists variable names, not entered values. This operation requires a
171
- write-enabled profile (also for previews), but no development update set.
172
- Confirmation follows the existing profile policy; automation can supply `--force`
173
- only for an approved order. Timeout or incomplete response is an uncertain
174
- outcome: inspect requests before retrying. JSN does not automatically submit a
175
- second order. `create/list/show` retain their definition-management behavior.
192
+ RITM directly. `order_now` returns the request (REQ); JSN then reads the request's
193
+ items and reports `request_id`, `request_number` and `requested_items`
194
+ (`sys_id`/`number`). If that follow-up read is denied, the order is still
195
+ reported as placed with `requested_items_readable: false` — inspect requests
196
+ rather than resubmitting. The command handles standard catalog items; record
197
+ producers and order guides require separate workflows. Server rules validate
198
+ dynamic variables at submission; a preview does not validate those rules.
199
+ Preview output lists variable names and required names, not entered values.
200
+ Previews only read, so they work on a read-only profile; submitting requires a
201
+ write-enabled profile and no development update set. Confirmation follows the
202
+ existing profile policy; automation can supply `--force` only for an approved
203
+ order. Timeout or incomplete response is an uncertain outcome: inspect requests
204
+ before retrying. JSN does not automatically submit a second order.
205
+ `create/list/show` retain their definition-management behavior.
176
206
 
177
207
  See the [Service Catalog API reference](https://www.servicenow.com/docs/r/api-reference/rest-apis/c_ServiceCatalogAPI.html).
178
208
 
209
+ ### Viewing service and HR cases
210
+
211
+ `jsn cases list`, `jsn cases show <number>` and `jsn cases search "<text>"` read
212
+ cases through the normal authenticated Table API. Which case table is meant
213
+ depends on the installed application, so JSN probes the known case tables in
214
+ order — `sn_customerservice_case` (Customer Service Management), then
215
+ `sn_hr_core_case` (HR Service Delivery) — and uses the first one the profile can
216
+ read. `jsn cases tables` reports each candidate without claiming access, and
217
+ `--table <name>` names any other case table.
218
+
219
+ ```bash
220
+ jsn cases list --json
221
+ jsn cases list --hr --query "active=true"
222
+ jsn cases search "printer" --table sn_customerservice_case
223
+ jsn cases show CS0001001
224
+ ```
225
+
226
+ Visibility is not widened by JSN: application roles and ACLs decide which
227
+ records are returned, and a denied table reports `forbidden` (HTTP 403) rather
228
+ than an empty list. An instance without a case application reports which tables
229
+ were unavailable instead of pretending there are no cases, and naming such a
230
+ table with `--table` fails the same way (`Reading <table> failed (HTTP 400)`,
231
+ exit 2) instead of printing an empty list. To scope a list to the connected
232
+ account, add a query term — field names differ per application, for example
233
+ `--query "opened_by=javascript:gs.getUserID()"`. These commands only read; case
234
+ work that changes state stays in the application UI or `jsn records update`.
235
+
236
+ HR cases are a thin addition over this generic path: `--hr` selects
237
+ `sn_hr_core_case`. Employee self-service visibility depends on the HR roles and
238
+ ACLs of the connected account — an administrator profile does not represent an
239
+ employee's view. HR case tasks, relations and the employee portal's widgets are
240
+ not exposed yet.
241
+
179
242
  ## Domain configuration and browser sessions
180
243
 
181
244
  `jsn domains current` reports the selected profile's configured `X-Now-Domain`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jacebenson/jsn",
3
- "version": "5.1.1",
3
+ "version": "5.2.0-dev.130.1",
4
4
  "description": "A command-line interface for ServiceNow that follows the Unix philosophy: simple, composable, and scriptable.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/app.js CHANGED
@@ -139,6 +139,10 @@ export class App {
139
139
 
140
140
  const scopeFormatted = `[${scope}]`;
141
141
 
142
+ // Terminal hyperlinks are invisible in a TTY and garbage in a pipe, so the
143
+ // banner only wraps values when stderr is actually a terminal.
144
+ const link = (text, url) => (process.stderr.isTTY === true ? hyperlink(text, url) : text);
145
+
142
146
  // Read-only profiles get a lock badge on every command run, so the
143
147
  // armed safety is always visible (not just in `auth status`).
144
148
  const roBadge = this.session?.readOnly === true ? ' 🔒' : '';
@@ -146,10 +150,10 @@ export class App {
146
150
  process.stderr.write('# Use `jsn scopes` to change scope, `jsn updatesets set` to change updateset\n');
147
151
  process.stderr.write('PROFILE USER [SCOPE] UPDATE SET\n');
148
152
 
149
- const profileStr = `${hyperlink(String(this.context.profileName).padEnd(9), instanceLink)}${roBadge}`;
150
- const userStr = hyperlink(String(displayUserName).padEnd(9), userLink);
151
- const scopeStr = hyperlink(String(scopeFormatted).padEnd(17), scopeLink);
152
- const updateSetStr = hyperlink(String(updateSet), updateSetLink);
153
+ const profileStr = `${link(String(this.context.profileName).padEnd(9), instanceLink)}${roBadge}`;
154
+ const userStr = link(String(displayUserName).padEnd(9), userLink);
155
+ const scopeStr = link(String(scopeFormatted).padEnd(17), scopeLink);
156
+ const updateSetStr = link(String(updateSet), updateSetLink);
153
157
 
154
158
  process.stderr.write(`${profileStr} ${userStr} ${scopeStr} ${updateSetStr}\n\n`);
155
159
 
package/src/cli.js CHANGED
@@ -34,6 +34,7 @@ import { groupsCmd } from './commands/groups.js';
34
34
  import { groupMembersCmd } from './commands/groupmembers.js';
35
35
  import { groupRolesCmd } from './commands/grouproles.js';
36
36
  import { ticketsCmd } from './commands/tickets.js';
37
+ import { casesCmd } from './commands/cases.js';
37
38
  import { transactionsCmd } from './commands/transactions.js';
38
39
 
39
40
  import { platformCmd } from './commands/platform.js';
@@ -353,6 +354,7 @@ export function buildCLI() {
353
354
  .command(requestsCmd(wrap))
354
355
  .command(tasksCmd(wrap))
355
356
  .command(catalogCmd(wrap))
357
+ .command(casesCmd(wrap))
356
358
  // AUTOMATION — Async
357
359
  .command(flowsCmd(wrap))
358
360
  .command(actionsCmd(wrap))
@@ -6,7 +6,7 @@ const BASIC_COMMANDS = new Set([
6
6
  'groups', 'groupmembers', 'grouproles', 'users', 'setup', 'auth', 'skill',
7
7
  'cmdb',
8
8
  'version', 'upgrade', 'docs', 'history', 'discover', 'completion',
9
- 'catalogitems',
9
+ 'catalogitems', 'cases',
10
10
  ]);
11
11
 
12
12
  export async function detectCommandAudience(sdk, username, instanceURL = sdk?.baseURL) {
@@ -311,6 +311,9 @@ export function buildDevCmd(name, table, aliases, defaultColumns, wrap, opts = {
311
311
  console.log(' update Update a record');
312
312
  console.log(' delete Delete a record');
313
313
  }
314
+ for (const sub of opts.extraSubcommands || []) {
315
+ console.log(` ${sub.name.padEnd(12)}${sub.description}`);
316
+ }
314
317
  console.log(`\nRun "jsn ${name} <command> --help" for details.`);
315
318
  },
316
319
  };
@@ -1,5 +1,6 @@
1
1
  import { buildProfileCommand } from '../record-profiles.js';
2
2
  import { getStringField } from '../helpers.js';
3
+ import { withTableBehavior } from './table-behavior.js';
3
4
  // Simple table-based commands — singular names passed for grammar
4
5
  // Default columns and aliases match the Go version exactly
5
6
 
@@ -62,7 +63,7 @@ export const uiActionsCmd = (wrap) => buildProfileCommand('uiactions', wrap);
62
63
  // this module's uiPoliciesCmd before uipoliciesCmd — so the factory version
63
64
  // was dead code shadowing nothing. Deleted; the re-export is the behavior.
64
65
 
65
- export const tablesCmd = (wrap) => buildProfileCommand('tables', wrap, {
66
+ export const tablesCmd = (wrap) => withTableBehavior(buildProfileCommand('tables', wrap, {
66
67
  async onShow(record, app) {
67
68
  const tableName = getStringField(record, 'name');
68
69
  const [count, extChain] = await Promise.all([
@@ -72,7 +73,8 @@ export const tablesCmd = (wrap) => buildProfileCommand('tables', wrap, {
72
73
  record._column_count = count;
73
74
  record._extension_info = { chain: extChain };
74
75
  },
75
- });
76
+ extraSubcommands: [{ name: 'behavior', description: 'Read-only behavior inventory (dictionary, ACLs, rules, scripts, actions, policies, notifications, styles, views, flow triggers)' }],
77
+ }), wrap);
76
78
 
77
79
  export { columnsCmd } from './columns.js';
78
80
 
@@ -0,0 +1,218 @@
1
+ // End-user case views: list/show/search over the case table the account can
2
+ // actually read. Which "case" a person means depends on the installed
3
+ // application, so the table is detected (or named explicitly) instead of
4
+ // assuming one product's schema. Reads only — every request goes through the
5
+ // normal authenticated Table API, so application roles and ACLs decide
6
+ // visibility; nothing here widens or bypasses them.
7
+ import { AppError, CodeForbidden, errUsage, errUsageHint } from '../errors.js';
8
+ import { buildQuerySuffix, formatCommandList, formatRecordForDisplay, getStringField, quoteShellArg, resolveFieldsParam } from '../helpers.js';
9
+ import { getRecord, listRecords, recordListParams } from '../records-engine.js';
10
+ import { declareCapabilities } from '../capabilities.js';
11
+
12
+ declareCapabilities('cases', {}); // read-only: no mutating subcommands
13
+
14
+ const TABLE = /^[a-z][a-z0-9_]*$/i;
15
+ const DEFAULT_COLUMNS = ['number', 'short_description', 'state', 'opened_by', 'sys_updated_on'];
16
+
17
+ // Detection order is presentation policy, not an access claim: each candidate
18
+ // is probed with the caller's own credentials.
19
+ const CASE_SOURCES = [
20
+ { table: 'sn_customerservice_case', application: 'Customer Service Management', label: 'customer service case' },
21
+ { table: 'sn_hr_core_case', application: 'HR Service Delivery', label: 'HR case' },
22
+ ];
23
+
24
+ function sourceFor(table) { return CASE_SOURCES.find(source => source.table === table); }
25
+ function requireTableName(table) {
26
+ if (!TABLE.test(table || '')) throw errUsage('--table takes a table name such as sn_customerservice_case or sn_hr_core_case.');
27
+ return table;
28
+ }
29
+
30
+ /** Turn one failed case read into an honest error class. */
31
+ function caseReadError(table, error) {
32
+ const status = error?.status;
33
+ if (status === 401) return error; // already normalized by errAPI
34
+ if (status === 403) {
35
+ return new AppError(CodeForbidden, `Access to ${table} is denied for this account (HTTP 403).`,
36
+ 'Case visibility follows the application roles and ACLs. Ask an administrator for access, or use a profile that has it.', 403);
37
+ }
38
+ if (status === 400 || status === 404) {
39
+ return errUsageHint(`Reading ${table} failed (HTTP ${status}).`,
40
+ 'The case application may not be installed, or the query uses a field this table does not have. Try jsn cases tables, then --table with a supported table.');
41
+ }
42
+ return error;
43
+ }
44
+
45
+ /** One read-only availability probe. Authentication failures are not a table fact. */
46
+ async function probe(app, table) {
47
+ const params = new URLSearchParams({ sysparm_limit: '1', sysparm_fields: 'sys_id', sysparm_display_value: 'false' });
48
+ try {
49
+ await app.sdk.list(table, params);
50
+ return { available: true };
51
+ } catch (error) {
52
+ if (error?.status === 401) throw error;
53
+ if (error?.status === 403) return { available: false, reason: 'denied (HTTP 403)', status: 403 };
54
+ if (error?.status === 400 || error?.status === 404) return { available: false, reason: `not installed (HTTP ${error.status})`, status: error.status };
55
+ throw error;
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Pick the case table to read: --hr and --table are explicit, otherwise probe
61
+ * the known case applications in order and use the first readable one.
62
+ */
63
+ async function resolveTable(app, argv) {
64
+ const explicit = argv.hr ? 'sn_hr_core_case' : argv.table === undefined ? undefined : requireTableName(argv.table);
65
+ if (argv.hr && argv.table !== undefined && argv.table !== 'sn_hr_core_case') throw errUsage('Choose --hr or --table, not both.');
66
+ if (explicit) {
67
+ const source = sourceFor(explicit);
68
+ return { table: explicit, application: source?.application ?? null, label: source?.label ?? 'case', source: 'explicit' };
69
+ }
70
+ const attempts = [];
71
+ for (const source of CASE_SOURCES) {
72
+ const probeResult = await probe(app, source.table);
73
+ attempts.push({ ...source, ...probeResult });
74
+ if (probeResult.available) return { ...source, source: 'detected', attempts };
75
+ }
76
+ const summary = attempts.map(a => `${a.table} ${a.reason}`).join('; ');
77
+ if (attempts.some(a => a.status === 403)) {
78
+ throw new AppError(CodeForbidden, `No readable case table for this account: ${summary}.`,
79
+ 'Case visibility follows the application roles and ACLs. Ask an administrator for case access, or use a profile that has it.', 403);
80
+ }
81
+ throw errUsageHint(
82
+ `No readable case table on this instance: ${summary}.`,
83
+ 'Install a case application (Customer Service Management or HR Service Delivery) and use an account with case access, or name a table explicitly with --table.',
84
+ );
85
+ }
86
+
87
+ async function listCases(app, argv, resolved, query) {
88
+ const columns = argv.columns ? argv.columns.split(',') : DEFAULT_COLUMNS;
89
+ const fields = resolveFieldsParam(columns);
90
+ const ordered = query ? `${query}^ORDERBYDESCsys_updated_on` : 'ORDERBYDESCsys_updated_on';
91
+ const params = recordListParams({ limit: argv.limit, offset: argv.offset, fields, query: ordered });
92
+ let records;
93
+ try {
94
+ records = await listRecords(app.sdk, { table: resolved.table, params, displayValues: argv.displayValues });
95
+ } catch (error) {
96
+ throw caseReadError(resolved.table, error);
97
+ }
98
+ const displayRecords = fields && !argv.displayValues ? records.map(r => formatRecordForDisplay(r, columns)) : records;
99
+ const breadcrumbs = [
100
+ { action: 'search', cmd: `jsn cases search "<text>"${argv.hr ? ' --hr' : ''}`, description: 'Search cases' },
101
+ ];
102
+ if (records.length === argv.limit) {
103
+ breadcrumbs.push({ action: 'next', cmd: `jsn cases list --limit ${argv.limit} --offset ${argv.offset + argv.limit}${buildQuerySuffix(argv.query)}`, description: 'Next page' });
104
+ }
105
+ if (argv.offset > 0) {
106
+ breadcrumbs.push({ action: 'prev', cmd: `jsn cases list --limit ${argv.limit} --offset ${Math.max(0, argv.offset - argv.limit)}${buildQuerySuffix(argv.query)}`, description: 'Previous page' });
107
+ }
108
+ app.ok({
109
+ table: resolved.table,
110
+ application: resolved.application,
111
+ table_source: resolved.source,
112
+ count: records.length,
113
+ columns,
114
+ records: displayRecords,
115
+ pagination: { limit: argv.limit, offset: argv.offset },
116
+ context: { instance_url: app.getEffectiveInstance() },
117
+ }, { summary: `${records.length} ${resolved.table}(s)`, breadcrumbs });
118
+ }
119
+
120
+ function listOptions(y) {
121
+ return y
122
+ .option('table', { type: 'string', describe: 'Case table to read (default: detected from installed case applications)' })
123
+ .option('hr', { type: 'boolean', default: false, describe: 'Read the HR case table (sn_hr_core_case)' })
124
+ .option('query', { type: 'string', describe: 'Encoded query (e.g. "active=true")' })
125
+ .option('columns', { alias: ['c', 'fields'], type: 'string', describe: 'Comma-separated columns' })
126
+ .option('limit', { alias: 'l', type: 'number', default: 20, describe: 'Max records' })
127
+ .option('offset', { alias: 'o', type: 'number', default: 0, describe: 'Offset' })
128
+ .option('display-values', { type: 'string', choices: ['raw', 'display', 'both'], describe: 'Reference values: raw, display or both' });
129
+ }
130
+
131
+ function showOptions(y) {
132
+ return y
133
+ .option('table', { type: 'string', describe: 'Case table to read (default: detected from installed case applications)' })
134
+ .option('hr', { type: 'boolean', default: false, describe: 'Read the HR case table (sn_hr_core_case)' })
135
+ .option('display-values', { type: 'string', choices: ['raw', 'display', 'both'], describe: 'Reference values: raw, display or both' });
136
+ }
137
+
138
+ function requireText(text) {
139
+ if (typeof text !== 'string' || !text.trim()) throw errUsage('Provide nonempty search text.');
140
+ if (text.includes('^')) throw errUsage('Search text cannot contain ^ (it separates encoded-query terms).');
141
+ return text.trim();
142
+ }
143
+
144
+ export function casesCmd(wrap) {
145
+ return {
146
+ command: 'cases [subcommand]',
147
+ aliases: ['case'],
148
+ describe: 'List, show or search service and HR cases visible to the connected account',
149
+ builder: (yargs) => yargs
150
+ .command({
151
+ command: 'list',
152
+ aliases: ['ls'],
153
+ describe: 'List cases the connected account can read',
154
+ builder: listOptions,
155
+ handler: wrap(async (argv, app) => {
156
+ const resolved = await resolveTable(app, argv);
157
+ await listCases(app, argv, resolved, argv.query || '');
158
+ }),
159
+ })
160
+ .command({
161
+ command: 'search <text>',
162
+ describe: 'Search case number and short description',
163
+ builder: y => listOptions(y).positional('text', { type: 'string' }),
164
+ handler: wrap(async (argv, app) => {
165
+ const text = requireText(argv.text);
166
+ const resolved = await resolveTable(app, argv);
167
+ await listCases(app, argv, resolved, `numberLIKE${text}^ORshort_descriptionLIKE${text}`);
168
+ }),
169
+ })
170
+ .command({
171
+ command: 'show <number>',
172
+ aliases: ['get'],
173
+ describe: 'Show one case by number',
174
+ builder: showOptions,
175
+ handler: wrap(async (argv, app) => {
176
+ const resolved = await resolveTable(app, argv);
177
+ let record;
178
+ try {
179
+ record = await getRecord(app.sdk, { table: resolved.table, identifier: argv.number, matchField: 'number', displayValues: argv.displayValues, resource: resolved.label });
180
+ } catch (error) {
181
+ throw caseReadError(resolved.table, error);
182
+ }
183
+ record._context = { instance_url: app.getEffectiveInstance(), table: resolved.table };
184
+ app.ok(record, {
185
+ summary: `${resolved.label.charAt(0).toUpperCase() + resolved.label.slice(1)} ${getStringField(record, 'number') || argv.number}`,
186
+ breadcrumbs: [
187
+ { action: 'list', cmd: `jsn cases list${argv.hr ? ' --hr' : argv.table ? ` --table ${quoteShellArg(argv.table)}` : ''}`, description: 'Back to cases' },
188
+ ],
189
+ });
190
+ }),
191
+ })
192
+ .command({
193
+ command: 'tables',
194
+ describe: 'Report which case applications this instance exposes to the account',
195
+ handler: wrap(async (argv, app) => {
196
+ const sources = [];
197
+ for (const source of CASE_SOURCES) {
198
+ const probeResult = await probe(app, source.table);
199
+ sources.push({ ...source, ...probeResult });
200
+ }
201
+ app.ok({ sources, available: sources.filter(s => s.available).map(s => s.table) },
202
+ { summary: sources.filter(s => s.available).length ? `Case tables: ${sources.filter(s => s.available).map(s => s.table).join(', ')}` : 'No readable case table found',
203
+ breadcrumbs: [{ action: 'list', cmd: 'jsn cases list', description: 'List cases' }] });
204
+ }),
205
+ })
206
+ .epilogue([
207
+ 'Default table: the first readable case application (Customer Service Management, then HR Service Delivery).',
208
+ 'Use --hr for sn_hr_core_case or --table <name> for any case table you can read; jsn cases tables reports each one.',
209
+ 'Reads use the caller\'s own credentials and ACLs. Self-service scoping is a query, not a bypass, and field names differ per application:',
210
+ ' jsn cases list --query "opened_by=javascript:gs.getUserID()" --hr',
211
+ 'Nothing here changes a case; use the application UI or records update for case work.',
212
+ ].join('\n')),
213
+ handler: wrap(async (argv, app) => app.ok({ subcommands: argv.subcommands || [],
214
+ _formatted: formatCommandList({ title: 'Cases', commands: argv.subcommands || [] }) },
215
+ { summary: 'Cases: list, show and search service or HR cases visible to the connected account',
216
+ breadcrumbs: [{ action: 'list', cmd: 'jsn cases list' + (argv.profile ? ` --profile ${quoteShellArg(argv.profile)}` : argv.instance ? ` --instance ${quoteShellArg(argv.instance)}` : ''), description: 'List visible cases' }] })),
217
+ };
218
+ }