@jacebenson/jsn 5.4.0-dev.149.1 → 5.4.0-dev.151.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jacebenson/jsn",
3
- "version": "5.4.0-dev.149.1",
3
+ "version": "5.4.0-dev.151.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": {
@@ -53,8 +53,8 @@ export default {
53
53
  options: { singular: 'UI macro', scopeValidation: true } },
54
54
  uxlists: { table: 'sys_ux_list', aliases: ['uxlist'], columns: ['name', 'active', 'sys_scope'],
55
55
  options: { singular: 'workspace list', scopeValidation: true, readOnly: true } },
56
- uxapplicability: { table: 'sys_ux_applicability_m2m', aliases: ['uxapp'], columns: ['name', 'active', 'sys_scope'],
57
- options: { singular: 'workspace applicability', scopeValidation: true, readOnly: true } },
56
+ uxapplicability: { table: 'sys_ux_applicability_m2m_list', aliases: ['uxapp'], columns: ['list', 'applicability', 'active', 'order', 'sys_scope'],
57
+ identifierField: 'sys_id', options: { singular: 'workspace applicability', scopeValidation: true, readOnly: true } },
58
58
  cataloguipolicies: { table: 'catalog_ui_policy', aliases: ['cataloguipolicy', 'cup'], columns: ['short_description', 'catalog_item', 'variable_set', 'active', 'sys_scope'],
59
59
  options: { singular: 'catalog UI policy', scopeValidation: true } },
60
60
  tables: { table: 'sys_db_object', aliases: ['table', 't'], columns: ['name', 'label', 'super_class', 'create_access_controls'],
@@ -341,6 +341,117 @@ function newestFirst(a, b) {
341
341
  return b.created_on.localeCompare(a.created_on) || a.sys_id.localeCompare(b.sys_id);
342
342
  }
343
343
 
344
+ // Only dictionary-typed durations are offsets; an epoch-shaped date is still a date.
345
+ function durationDisplay(value) {
346
+ if (!/^1970-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(value)) return value;
347
+ const milliseconds = Date.parse(`${value.replace(' ', 'T')}Z`);
348
+ if (!Number.isFinite(milliseconds) || milliseconds < 0
349
+ || new Date(milliseconds).toISOString().slice(0, 19) !== value.replace(' ', 'T')) return value;
350
+ let seconds = milliseconds / 1000;
351
+ const parts = [];
352
+ for (const [unit, size] of [['day', 86400], ['hour', 3600], ['minute', 60], ['second', 1]]) {
353
+ const count = Math.floor(seconds / size);
354
+ seconds %= size;
355
+ if (count) parts.push(`${count} ${unit}${count === 1 ? '' : 's'}`);
356
+ }
357
+ return parts.join(' ') || '0 seconds';
358
+ }
359
+
360
+ // Resolve the declared target table's display column, including inherited columns.
361
+ // Cache metadata (and failures) per table for this inspection, never per activity.
362
+ async function configurationValues(sdk, rows) {
363
+ const metadata = new Map();
364
+ const targets = new Map();
365
+ const identifier = value => /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(value);
366
+ async function lookup(table, options) {
367
+ // These reads only enrich values. A failed enrichment must not hide the
368
+ // original ID or make an otherwise readable workflow unavailable.
369
+ try {
370
+ return await readComponent(sdk, table, options);
371
+ } catch {
372
+ return { state: 'unavailable', rows: [] };
373
+ }
374
+ }
375
+ async function displayField(table, seen = new Set()) {
376
+ if (!identifier(table) || seen.has(table) || seen.size >= 16) return '';
377
+ if (metadata.has(table)) return metadata.get(table);
378
+ seen.add(table);
379
+ const dictionary = await lookup('sys_dictionary', {
380
+ query: `name=${table}^display=true`, fields: 'element', limit: 2,
381
+ });
382
+ let field = dictionary.rows?.length === 1 ? raw(dictionary.rows[0].element) : '';
383
+ if (!field && dictionary.state === 'ok' && !dictionary.rows.length) {
384
+ const parent = await lookup('sys_db_object', {
385
+ query: `name=${table}`, fields: 'super_class.name', limit: 2,
386
+ });
387
+ if (parent.rows?.length === 1) field = await displayField(raw(parent.rows[0]['super_class.name']), seen);
388
+ }
389
+ if (!field && dictionary.state === 'ok') {
390
+ // ServiceNow can use its conventional name/number column without an
391
+ // explicit display=true dictionary entry (e.g. sys_user_group).
392
+ const defaults = await lookup('sys_dictionary', {
393
+ query: `name=${table}^elementINname,number`, fields: 'element', limit: 2,
394
+ });
395
+ const elements = new Set((defaults.rows || []).map(row => raw(row.element)));
396
+ field = ['name', 'number'].find(element => elements.has(element)) || '';
397
+ }
398
+ field = identifier(field) ? field : '';
399
+ metadata.set(table, field);
400
+ return field;
401
+ }
402
+ const values = rows.map(row => {
403
+ const type = raw(row['variable.internal_type']);
404
+ const value = raw(row.value);
405
+ const table = raw(row['variable.reference']);
406
+ const info = { raw_value: value, display_value: text(row.value), type, reference_table: table };
407
+ if (type === 'glide_duration') info.display_value = durationDisplay(value);
408
+ if (['reference', 'glide_list'].includes(type) && value.trim()) {
409
+ const ids = value.split(',').map(id => id.trim());
410
+ info.resolution = 'unresolved';
411
+ if (info.display_value.trim() && info.display_value !== value
412
+ && !info.display_value.split(',').every(id => isSysId(id.trim()))) {
413
+ info.resolution = 'resolved';
414
+ } else if (identifier(table) && ids.every(isSysId)) {
415
+ if (!targets.has(table)) targets.set(table, new Set());
416
+ for (const id of ids) targets.get(table).add(id);
417
+ }
418
+ }
419
+ return info;
420
+ });
421
+ const names = new Map();
422
+ for (const [table, ids] of targets) {
423
+ const field = await displayField(table);
424
+ if (!field) continue;
425
+ for (const chunk of chunks([...ids])) {
426
+ const records = await lookup(table, {
427
+ query: `sys_idIN${chunk.join(',')}`, fields: `sys_id,${field}`, limit: CHUNK,
428
+ });
429
+ for (const record of records.rows || []) {
430
+ const name = text(record[field]).trim();
431
+ if (name && name !== raw(record.sys_id)) names.set(`${table}:${raw(record.sys_id)}`, name);
432
+ }
433
+ }
434
+ }
435
+ for (const info of values) {
436
+ if (info.resolution !== 'unresolved') continue;
437
+ let resolved = true;
438
+ info.display_value = info.raw_value.split(',').map(value => {
439
+ const id = value.trim();
440
+ // A reference field may legitimately hold a template expression, a script
441
+ // variable or plain text (for example "${opened_by}"). Only a 32-hex sys_id
442
+ // can be a reference, so anything else is passed through untouched and must
443
+ // not be reported as an unresolved reference.
444
+ if (!/^[0-9a-f]{32}$/i.test(id)) return value;
445
+ const name = names.get(`${info.reference_table}:${id}`);
446
+ if (name) return name;
447
+ resolved = false;
448
+ return `${id} (unresolved reference)`;
449
+ }).join(', ');
450
+ info.resolution = resolved ? 'resolved' : 'unresolved';
451
+ }
452
+ return values;
453
+ }
454
+
344
455
  function isScriptField(element) {
345
456
  return element === 'script' || element.startsWith('script_') || element.endsWith('_script');
346
457
  }
@@ -541,7 +652,7 @@ export async function inspectWorkflow(sdk, {
541
652
  for (const chunk of chunks(activityIds)) {
542
653
  configurationReads.push(await readComponent(sdk, VARIABLE_VALUE, {
543
654
  query: `document=wf_activity^document_keyIN${chunk.join(',')}^ORDERBYorder`,
544
- fields: 'document_key,variable.element,value',
655
+ fields: 'document_key,variable.element,variable.internal_type,variable.reference,value',
545
656
  limit: MAX_LIMIT,
546
657
  }));
547
658
  }
@@ -552,15 +663,23 @@ export async function inspectWorkflow(sdk, {
552
663
  inaccessible.push({ component: 'configuration', state: failed.state, http_status: failed.http_status ?? null, code: failed.code ?? null });
553
664
  }
554
665
  const byActivity = new Map();
555
- for (const row of configurationReads.flatMap(read => read.rows || [])) {
666
+ const detailsByActivity = new Map();
667
+ const configurationRows = configurationReads.flatMap(read => read.rows || []);
668
+ const values = await configurationValues(sdk, configurationRows);
669
+ for (const [index, row] of configurationRows.entries()) {
556
670
  const activityId = raw(row.document_key);
557
671
  const element = raw(row['variable.element']);
558
672
  if (!activityId || !element) continue;
559
673
  if (!byActivity.has(activityId)) byActivity.set(activityId, {});
560
- byActivity.get(activityId)[element] = text(row.value);
674
+ byActivity.get(activityId)[element] = values[index].type ? raw(row.value) : text(row.value);
675
+ if (values[index].type) {
676
+ if (!detailsByActivity.has(activityId)) detailsByActivity.set(activityId, {});
677
+ detailsByActivity.get(activityId)[element] = values[index];
678
+ }
561
679
  }
562
680
  for (const activity of activities) {
563
681
  activity.configuration = byActivity.get(activity.sys_id) || {};
682
+ if (detailsByActivity.has(activity.sys_id)) activity.configuration_values = detailsByActivity.get(activity.sys_id);
564
683
  activity.configuration_omissions = [];
565
684
  for (const [element, value] of Object.entries(activity.configuration)) {
566
685
  if (isScriptField(element) && isCommentOnlyScript(value)) {
@@ -769,7 +888,8 @@ function formatStepContent(activity, full = false) {
769
888
  .sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
770
889
  const width = Math.max(0, ...entries.map(([field]) => field.length + 1));
771
890
  for (const [field, value] of entries) {
772
- const valueLines = (full ? String(value) : String(value).trim()).split(/\r?\n/);
891
+ const display = activity.configuration_values?.[field]?.display_value ?? value;
892
+ const valueLines = (full ? String(display) : String(display).trim()).split(/\r?\n/);
773
893
  const prefix = ` ${`${field}:`.padEnd(width)} `;
774
894
  const continuation = ' '.repeat(prefix.length);
775
895
  const visible = full ? valueLines : valueLines.slice(0, 3);