@jacebenson/jsn 5.5.1 → 5.5.2-dev.174.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.
Files changed (51) hide show
  1. package/README.md +30 -2
  2. package/package.json +1 -1
  3. package/src/app.js +15 -2
  4. package/src/auth/mfa.js +85 -0
  5. package/src/cli-adapter.js +18 -4
  6. package/src/cli.js +26 -8
  7. package/src/commands/_generic.js +10 -2
  8. package/src/commands/_ticket.js +12 -4
  9. package/src/commands/approvals.js +1 -0
  10. package/src/commands/auth.js +15 -8
  11. package/src/commands/cases.js +1 -1
  12. package/src/commands/cmdb.js +1 -1
  13. package/src/commands/discover.js +1 -0
  14. package/src/commands/docs/client.js +17 -7
  15. package/src/commands/docs/community.js +4 -4
  16. package/src/commands/docs/db.js +26 -11
  17. package/src/commands/docs/docs.js +30 -13
  18. package/src/commands/docs/embed.js +2 -2
  19. package/src/commands/docs/index-worker.js +1 -1
  20. package/src/commands/docs/index.js +4 -3
  21. package/src/commands/docs/ingest.js +4 -4
  22. package/src/commands/docs/install.js +19 -17
  23. package/src/commands/docs/local.js +6 -4
  24. package/src/commands/docs/refresh.js +3 -3
  25. package/src/commands/docs/releases.js +27 -0
  26. package/src/commands/docs/search.js +3 -3
  27. package/src/commands/docs/serve.js +3 -3
  28. package/src/commands/docs/server.js +13 -10
  29. package/src/commands/docs/service-snapshot.js +3 -3
  30. package/src/commands/docs/snapshot.js +32 -11
  31. package/src/commands/docs/sync-service.js +8 -6
  32. package/src/commands/docs/sync.js +24 -15
  33. package/src/commands/flows.js +70 -5
  34. package/src/commands/knowledge.js +1 -0
  35. package/src/commands/records.js +12 -3
  36. package/src/commands/setup.js +20 -8
  37. package/src/commands/tickets.js +11 -3
  38. package/src/errors.js +23 -1
  39. package/src/flow-create.js +1237 -57
  40. package/src/flow-inspection.js +26 -2
  41. package/src/help.js +95 -21
  42. package/src/helpers.js +20 -1
  43. package/src/output.js +19 -5
  44. package/src/prompts.js +9 -0
  45. package/src/record-command-profiles.js +8 -4
  46. package/src/record-profiles.js +1 -0
  47. package/src/records-engine.js +2 -1
  48. package/src/sdk.js +157 -15
  49. package/src/setup-preferences.js +3 -3
  50. package/src/table-read-params.js +9 -0
  51. package/src/welcome.js +34 -36
@@ -4,7 +4,8 @@ import path from 'node:path';
4
4
  import { createHash, randomUUID } from 'node:crypto';
5
5
  import { gzipSync, gunzipSync } from 'node:zlib';
6
6
  import Database from 'better-sqlite3';
7
- import { getDocsDbPath, getDocsCacheDir } from './db.js';
7
+ import { resolveDocsDbPath, resolveDocsRelease, DEFAULT_DOCS_RELEASE } from './db.js';
8
+ import { docsServiceUrl } from './client.js';
8
9
  import { docsReaderLease } from './locks.js';
9
10
  import { ingestDocs } from './ingest.js';
10
11
  import { installDatabase } from './replace.js';
@@ -36,7 +37,7 @@ export function validateDatabase(filename) {
36
37
  return count;
37
38
  } finally { db.close(); }
38
39
  }
39
- export function buildSnapshot({ docsDir, outputDir, revision, artifactBaseURL, embed = true }) {
40
+ export function buildSnapshot({ docsDir, outputDir, revision, artifactBaseURL, embed = true, release }) {
40
41
  if (!/^[a-f0-9]{7,64}$/.test(revision || '')) throw new Error('A source commit revision is required');
41
42
  fs.mkdirSync(outputDir, { recursive: true });
42
43
  const temporary = fs.mkdtempSync(path.join(outputDir, '.build-'));
@@ -52,7 +53,7 @@ export function buildSnapshot({ docsDir, outputDir, revision, artifactBaseURL, e
52
53
  const documents = validateDatabase(filename);
53
54
  const bytes = fs.readFileSync(filename), compressed = gzipSync(bytes);
54
55
  const name = `docs-schema-${SNAPSHOT_SCHEMA}-${revision}.sqlite.gz`;
55
- const manifest = validateManifest({ format: 1, schema: SNAPSHOT_SCHEMA, cliCompatibility: 'docs-schema-1', revision,
56
+ const manifest = validateManifest({ format: 1, schema: SNAPSHOT_SCHEMA, cliCompatibility: 'docs-schema-1', revision, ...(release ? { release: resolveDocsRelease(release) } : {}),
56
57
  sha256: digest(compressed), compressedBytes: compressed.length, databaseBytes: bytes.length,
57
58
  documents, buildSeconds: result.secs, builtAt: new Date().toISOString(), url: new URL(name, artifactBaseURL.endsWith('/') ? artifactBaseURL : artifactBaseURL + '/').href });
58
59
  const artifact = path.join(outputDir, name);
@@ -68,7 +69,7 @@ export function buildSnapshot({ docsDir, outputDir, revision, artifactBaseURL, e
68
69
  async function download(url, maxBytes, fetchFn, timeout = 600000) {
69
70
  const response = await fetchFn(url, { signal: AbortSignal.timeout(timeout) });
70
71
  if (response.url && new URL(response.url).protocol !== 'https:' && !['localhost', '127.0.0.1', '[::1]'].includes(new URL(response.url).hostname)) throw new Error('Docs download redirected to insecure transport');
71
- if (!response.ok) throw new Error(`Docs download rejected (HTTP ${response.status})`);
72
+ if (!response.ok) throw Object.assign(new Error(`Docs download rejected (HTTP ${response.status})`), { status: response.status });
72
73
  if (Number(response.headers.get('content-length')) > maxBytes) { await response.body?.cancel(); throw new Error('Docs download exceeds size limit'); }
73
74
  const parts = []; let size = 0;
74
75
  for await (const chunk of response.body) {
@@ -83,11 +84,30 @@ export async function fetchManifest(url = DEFAULT_MANIFEST_URL, { fetchFn = fetc
83
84
  validateManifest({ format: 1, schema: 1, cliCompatibility: 'docs-schema-1', revision: 'abcdef0', sha256: '0'.repeat(64), compressedBytes: 1, databaseBytes: 1, url });
84
85
  return validateManifest(JSON.parse((await download(url, 65536, fetchFn, 15000)).toString('utf8')));
85
86
  }
87
+ export function validateManifestRelease(manifest, release, legacy = false) {
88
+ if (manifest.release !== undefined && manifest.release !== release) throw new Error(`Docs snapshot release ${manifest.release} does not match requested release ${release}; existing index retained`);
89
+ if (manifest.release === undefined && (!legacy || release !== DEFAULT_DOCS_RELEASE)) throw new Error(`Docs snapshot manifest must declare release ${release}; existing index retained`);
90
+ return manifest;
91
+ }
92
+ export async function fetchReleaseManifest({ release = DEFAULT_DOCS_RELEASE, serviceUrl, manifestURL, fetchFn = fetch } = {}) {
93
+ release = resolveDocsRelease(release);
94
+ if (manifestURL) return { manifest: validateManifestRelease(await fetchManifest(manifestURL, { fetchFn }), release, release === DEFAULT_DOCS_RELEASE), manifestURL };
95
+ const service = docsServiceUrl(serviceUrl);
96
+ const familyURL = new URL(`docs-index/releases/${release}/manifest.json`, service).href;
97
+ try { return { manifest: validateManifestRelease(await fetchManifest(familyURL, { fetchFn }), release), manifestURL: familyURL }; }
98
+ catch (error) {
99
+ if (release !== DEFAULT_DOCS_RELEASE || error.status !== 404) throw error;
100
+ const legacyURL = new URL('docs-index/manifest.json', service).href;
101
+ return { manifest: validateManifestRelease(await fetchManifest(legacyURL, { fetchFn }), release, true), manifestURL: legacyURL };
102
+ }
103
+ }
86
104
  export function snapshotEstimate(manifest) {
87
105
  return `${(manifest.compressedBytes / 1048576).toFixed(1)} MiB; estimated ${Math.max(1, Math.ceil(manifest.compressedBytes / 5242880))} seconds at 5 MiB/s plus verification (actual time varies)`;
88
106
  }
89
- export async function installSnapshot({ manifestURL = DEFAULT_MANIFEST_URL, manifest, dbPath = getDocsDbPath(), fetchFn = fetch } = {}) {
107
+ export async function installSnapshot({ release = DEFAULT_DOCS_RELEASE, manifestURL = DEFAULT_MANIFEST_URL, manifest, dbPath = resolveDocsDbPath(release), fetchFn = fetch } = {}) {
108
+ release = resolveDocsRelease(release);
90
109
  manifest = manifest ? validateManifest(manifest) : await fetchManifest(manifestURL, { fetchFn });
110
+ validateManifestRelease(manifest, release, release === DEFAULT_DOCS_RELEASE && !new URL(manifestURL).pathname.includes('/docs-index/releases/'));
91
111
  const compressed = await download(manifest.url, manifest.compressedBytes, fetchFn);
92
112
  if (compressed.length !== manifest.compressedBytes || digest(compressed) !== manifest.sha256) throw new Error('Docs snapshot checksum/size mismatch; existing index retained');
93
113
  const bytes = gunzipSync(compressed, { maxOutputLength: manifest.databaseBytes });
@@ -106,10 +126,10 @@ export async function installSnapshot({ manifestURL = DEFAULT_MANIFEST_URL, mani
106
126
  fs.writeFileSync(receiptStage, JSON.stringify({ ...manifest, manifestURL, checkedAt: Date.now() }), { mode: 0o600 });
107
127
  installDatabase(staged, dbPath, { afterInstall: () => fs.renameSync(receiptStage, receipt) });
108
128
  } finally { fs.rmSync(receiptStage, { force: true }); }
109
- return { revision: manifest.revision, documents: manifest.documents, dbPath, source: 'snapshot' };
129
+ return { release, revision: manifest.revision, documents: manifest.documents, dbPath, source: 'snapshot' };
110
130
  } finally { fs.rmSync(staged, { force: true }); }
111
131
  }
112
- export function rollbackSnapshot(dbPath = getDocsDbPath()) {
132
+ export function rollbackSnapshot(dbPath = resolveDocsDbPath()) {
113
133
  const previous = `${dbPath}.previous`;
114
134
  if (!fs.existsSync(previous)) throw new Error('No previous docs snapshot is available');
115
135
  validateDatabase(previous);
@@ -118,13 +138,14 @@ export function rollbackSnapshot(dbPath = getDocsDbPath()) {
118
138
  finally { fs.rmSync(staged, { force: true }); }
119
139
  return { dbPath, rolledBack: true };
120
140
  }
121
- export function docsSnapshotStatus() {
122
- const receipt = path.join(getDocsCacheDir(), 'docs.db.snapshot.json');
141
+ export function docsSnapshotStatus(family) {
142
+ const dbPath = resolveDocsDbPath(family);
143
+ const receipt = `${dbPath}.snapshot.json`;
123
144
  let release, db;
124
145
  try {
125
- release = docsReaderLease(getDocsDbPath());
146
+ release = docsReaderLease(dbPath);
126
147
  const value = JSON.parse(fs.readFileSync(receipt, 'utf8'));
127
- db = new Database(getDocsDbPath(), { readonly: true, fileMustExist: true });
148
+ db = new Database(dbPath, { readonly: true, fileMustExist: true });
128
149
  return db.prepare("SELECT value FROM meta WHERE key='snapshot_revision'").get()?.value === value.revision ? value : null;
129
150
  } catch { return null; } finally { db?.close(); release?.(); }
130
151
  }
@@ -10,6 +10,7 @@ import { ingestDocs } from './ingest.js';
10
10
  import { refreshDocs } from './refresh.js';
11
11
  import { installSnapshot } from './snapshot.js';
12
12
  import { publishServiceSnapshot } from './service-snapshot.js';
13
+ import { DEFAULT_DOCS_RELEASE, resolveDocsDbPath, resolveDocsRelease } from './db.js';
13
14
 
14
15
  const defaultStorage = path.join(process.env.JSN_DATA_HOME || path.join(os.homedir(), '.jsn'), 'docs-service');
15
16
  function git(args) {
@@ -25,10 +26,11 @@ function writeStatus(storage, status) {
25
26
  async function performSync(options = {}) {
26
27
  const storage = options.storage || process.env.DOCS_STORAGE_DIR || defaultStorage;
27
28
  const source = options.source || process.env.DOCS_SOURCE_URL || 'https://github.com/ServiceNow/ServiceNowDocs.git';
28
- const branch = options.branch || process.env.DOCS_SOURCE_BRANCH || 'australia';
29
+ const family = options.release || process.env.JSN_DOCS_RELEASE;
30
+ const branch = family ? resolveDocsRelease(family) : options.branch || process.env.DOCS_SOURCE_BRANCH || DEFAULT_DOCS_RELEASE;
29
31
  fs.mkdirSync(storage, { recursive: true });
30
32
  const repo = path.join(storage, 'source');
31
- const live = path.join(storage, 'docs.sqlite3');
33
+ const live = family ? resolveDocsDbPath(family) : path.join(storage, 'docs.sqlite3');
32
34
  const staging = path.join(storage, `build-${randomUUID()}.sqlite3`);
33
35
  let previous = {};
34
36
  try { previous = JSON.parse(fs.readFileSync(path.join(storage, 'status.json'), 'utf8')); } catch { /* first run */ }
@@ -43,7 +45,7 @@ async function performSync(options = {}) {
43
45
  try {
44
46
  // Only the first installation uses the hosted seed. Updates always use GitHub.
45
47
  // Custom source repositories must never be seeded with an unrelated corpus.
46
- if (!fs.existsSync(live) && ((!options.source && !process.env.DOCS_SOURCE_URL) || options.manifestURL) && branch === 'australia') {
48
+ if (!fs.existsSync(live) && ((!options.source && !process.env.DOCS_SOURCE_URL) || options.manifestURL) && branch === DEFAULT_DOCS_RELEASE) {
47
49
  try {
48
50
  const seed = await installSnapshot({ dbPath: live,
49
51
  manifestURL: options.manifestURL || process.env.DOCS_BOOTSTRAP_MANIFEST_URL,
@@ -67,7 +69,7 @@ async function performSync(options = {}) {
67
69
  try { current = db.prepare("SELECT value FROM meta WHERE key='source_revision'").get()?.value; }
68
70
  finally { db.close(); }
69
71
  if (remote && current === remote) {
70
- await publishServiceSnapshot(storage);
72
+ await publishServiceSnapshot(storage, { dbPath: live, release: family });
71
73
  const status = { ...previous, state: 'ready', revision: current, checkedAt: new Date().toISOString(), startedAt, error: null, changed: false };
72
74
  writeStatus(storage, status);
73
75
  return status;
@@ -97,7 +99,7 @@ async function performSync(options = {}) {
97
99
  } finally { db.close(); }
98
100
  }
99
101
  if (oldRevision === revision && !options.force) {
100
- await publishServiceSnapshot(storage);
102
+ await publishServiceSnapshot(storage, { dbPath: live, release: family });
101
103
  const status = { ...previous, state: 'ready', revision, checkedAt: new Date().toISOString(), startedAt, error: null, changed: false };
102
104
  writeStatus(storage, status);
103
105
  return status;
@@ -121,7 +123,7 @@ async function performSync(options = {}) {
121
123
  db.pragma('journal_mode = DELETE');
122
124
  } finally { db.close(); }
123
125
  fs.renameSync(staging, live);
124
- await publishServiceSnapshot(storage);
126
+ await publishServiceSnapshot(storage, { dbPath: live, release: family });
125
127
  const status = { state: 'ready', revision, documents: count, startedAt, checkedAt: new Date().toISOString(), publishedAt: new Date().toISOString(), changed: true, error: null, result };
126
128
  writeStatus(storage, status);
127
129
  return status;
@@ -4,15 +4,14 @@ import fs from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import { docsInstallLease, docsHaveReaders } from './locks.js';
6
6
  import { spawnSync } from 'node:child_process';
7
- import { getDocsSourceDir, getDocsSourceMarkdownDir, getDocsDbPath, docsDbExists } from './db.js';
7
+ import { getDocsSourceDir, getDocsSourceMarkdownDir, resolveDocsDbPath, resolveDocsRelease, withDocsDb, setMeta } from './db.js';
8
8
  import { ingestDocs } from './ingest.js';
9
9
  import { refreshDocs } from './refresh.js';
10
10
 
11
11
  const REPO_URL = 'https://github.com/ServiceNow/ServiceNowDocs';
12
- const BRANCH = 'australia';
13
12
 
14
13
  function git(args, cwd, stdio = 'inherit') {
15
- const r = spawnSync('git', args, { cwd, stdio });
14
+ const r = spawnSync('git', args, { cwd, stdio: stdio === 'inherit' ? ['ignore', 2, 2] : stdio });
16
15
  if (r.error && r.error.code === 'ENOENT') {
17
16
  throw new Error('git is not installed. Install git to sync docs, or download the docs repo manually.');
18
17
  }
@@ -22,7 +21,7 @@ function git(args, cwd, stdio = 'inherit') {
22
21
  }
23
22
 
24
23
  export function syncDocs(opts = {}) {
25
- const repoDir = opts.repoDir || getDocsSourceDir();
24
+ const repoDir = opts.repoDir || getDocsSourceDir(opts.release);
26
25
  fs.mkdirSync(path.dirname(repoDir), { recursive: true });
27
26
  const release = docsInstallLease(repoDir);
28
27
  try {
@@ -31,9 +30,10 @@ export function syncDocs(opts = {}) {
31
30
  } finally { release(); }
32
31
  }
33
32
  function syncDocsLocked(opts = {}) {
34
- const repoDir = opts.repoDir || getDocsSourceDir();
35
- const markdownDir = opts.markdownDir || getDocsSourceMarkdownDir();
36
- const dbPath = opts.dbPath || getDocsDbPath();
33
+ const repoDir = opts.repoDir || getDocsSourceDir(opts.release);
34
+ const markdownDir = opts.markdownDir || getDocsSourceMarkdownDir(opts.release);
35
+ const dbPath = opts.dbPath || resolveDocsDbPath(opts.release);
36
+ const branch = resolveDocsRelease(opts.release);
37
37
  const embed = opts.embed !== false;
38
38
  const noIngest = opts.noIngest === true;
39
39
 
@@ -53,14 +53,16 @@ function syncDocsLocked(opts = {}) {
53
53
 
54
54
  if (!initialStatus.clone) {
55
55
  process.stderr.write(`Updating existing clone at ${repoDir} ...\n`);
56
- git(['-C', repoDir, 'pull', '--ff-only'], repoDir, 'inherit');
56
+ git(['-C', repoDir, 'fetch', 'origin', branch], repoDir, 'inherit');
57
+ git(['-C', repoDir, 'checkout', branch], repoDir, 'inherit');
58
+ git(['-C', repoDir, 'merge', '--ff-only', 'FETCH_HEAD'], repoDir, 'inherit');
57
59
  } else {
58
60
  fs.mkdirSync(path.dirname(repoDir), { recursive: true });
59
- process.stderr.write(`Cloning ${REPO_URL} (branch ${BRANCH}) into ${repoDir} ...\n`);
61
+ process.stderr.write(`Cloning ${REPO_URL} (branch ${branch}) into ${repoDir} ...\n`);
60
62
  git([
61
63
  'clone',
62
64
  '--depth', '1',
63
- '--branch', BRANCH,
65
+ '--branch', branch,
64
66
  '--config', 'core.longpaths=true',
65
67
  REPO_URL,
66
68
  repoDir,
@@ -71,18 +73,25 @@ function syncDocsLocked(opts = {}) {
71
73
  throw new Error(`Expected markdown folder not found at ${markdownDir}.`);
72
74
  }
73
75
 
76
+ const revisionResult = spawnSync('git', ['-C', repoDir, 'rev-parse', 'HEAD'], { encoding: 'utf8' });
77
+ if (revisionResult.status !== 0) throw new Error('Could not read documentation source revision.');
78
+ const revision = revisionResult.stdout.trim();
79
+ const recordRevision = () => withDocsDb({ dbPath }, db => { setMeta(db, 'source_revision', revision); setMeta(db, 'source_branch', branch); });
80
+
74
81
  if (noIngest) {
75
82
  return { repoDir, markdownDir, dbPath, ingested: false, note: 'Run without --no-ingest to build the index.' };
76
83
  }
77
84
 
78
85
  // If the DB already exists, use incremental refresh. Otherwise, full ingest.
79
- if (docsDbExists()) {
86
+ if (fs.existsSync(dbPath)) {
80
87
  process.stderr.write(`Docs DB found — running incremental refresh...\n`);
81
- const result = refreshDocs({ docsDir: markdownDir, dbPath, sourceResource: repoDir, sourceLeaseHeld: true });
82
- return { repoDir, markdownDir, dbPath, ingested: true, incremental: true, ...result };
88
+ const result = refreshDocs({ release: branch, docsDir: markdownDir, dbPath, sourceResource: repoDir, sourceLeaseHeld: true });
89
+ recordRevision();
90
+ return { repoDir, markdownDir, dbPath, revision, ingested: true, incremental: true, ...result };
83
91
  }
84
92
 
85
93
  process.stderr.write('No existing DB — running full ingest...\n');
86
- const result = ingestDocs({ docsDir: markdownDir, dbPath, embed, sourceResource: repoDir, sourceLeaseHeld: true });
87
- return { repoDir, markdownDir, dbPath, ingested: true, incremental: false, ...result };
94
+ const result = ingestDocs({ release: branch, docsDir: markdownDir, dbPath, embed, sourceResource: repoDir, sourceLeaseHeld: true });
95
+ recordRevision();
96
+ return { repoDir, markdownDir, dbPath, revision, ingested: true, incremental: false, ...result };
88
97
  }
@@ -10,11 +10,29 @@ import { alignUpdateSetCapture } from '../context.js';
10
10
  import { EXCLUDED_TRIGGER_TYPES, SUPPORTED_TRIGGER_TYPES, readTriggerCatalog, readTriggerInputDefinitions } from '../flow-triggers.js';
11
11
  import { testFlow } from '../flow-test.js';
12
12
  import { releaseOwnFlowSafeEdit } from '../flow-safe-edit.js';
13
- import { errUsage } from '../errors.js';
13
+ import { AppError, CodeAPI, CodeForbidden, errUsage } from '../errors.js';
14
14
  import { cancelled, pickDesignerRecord, guidedFlowCreate, guidedFlowEdit, guidedFlowTestRecord, hasDefinitionData, confirmDesignerMutation } from '../flow-designer-interactive.js';
15
15
 
16
16
  const pickFlow = (argv, app, query = '') => pickDesignerRecord(argv, app, argv.action ? 'sys_hub_action_type_definition' : 'sys_hub_flow', argv.action ? 'action' : 'flow', query);
17
17
 
18
+ // Rows the provider cascades when the sys_hub_flow record is deleted. Counted
19
+ // before and after so the command reports what went with the flow.
20
+ const FLOW_OWNED_TABLES = [
21
+ { table: 'sys_hub_flow_version', label: 'version', query: id => `flow=${id}` },
22
+ { table: 'sys_hub_action_instance_v2', label: 'action instance', query: id => `flow=${id}` },
23
+ { table: 'sys_hub_flow_logic_instance_v2', label: 'logic block', query: id => `flow=${id}` },
24
+ { table: 'sys_hub_flow_stage', label: 'stage', query: id => `flow=${id}` },
25
+ // Flow variables hang off `model`, not `flow`.
26
+ { table: 'sys_hub_flow_variable', label: 'flow variable', query: id => `model=${id}` },
27
+ ];
28
+
29
+ function describeOwned(counts) {
30
+ const parts = Object.entries(counts)
31
+ .filter(([, count]) => count)
32
+ .map(([table, count]) => `${count} ${FLOW_OWNED_TABLES.find(entry => entry.table === table)?.label ?? table}${count === 1 ? '' : 's'}`);
33
+ return parts.length ? parts.join(', ') : 'nothing';
34
+ }
35
+
18
36
  const FLOW_COMMANDS = [
19
37
  { name: 'schemas', description: 'Read live trigger catalog and input schemas' },
20
38
  { name: 'catalog-variables [identifier]', description: 'List a catalog item\'s variables for a service_catalog trigger' },
@@ -28,7 +46,7 @@ const FLOW_COMMANDS = [
28
46
  { name: 'update [identifier]', description: 'Update a draft, or a published flow whose definition reports write access (alias: edit)' },
29
47
  { name: 'doctor', description: 'Check whether this instance can publish flows at all' },
30
48
  { name: 'unlock [identifier]', description: 'Release this user\'s stale safe-edit session (orphaned lease) after a failed update' },
31
- { name: 'delete [identifier]', description: 'Delete a flow (not implemented: use the Flow Designer UI)' },
49
+ { name: 'delete [identifier]', description: 'Delete a flow and the versions, actions, logic and stages it owns' },
32
50
  ];
33
51
 
34
52
  function flowInspectionAdapter(app) {
@@ -231,6 +249,11 @@ export function flowsCmd(wrap) {
231
249
  type: 'number',
232
250
  default: 2,
233
251
  describe: 'Expand nested subflows to this depth (1 = subflow names only, 2 = one level, 3+ = deeper)',
252
+ })
253
+ .option('raw-payload', {
254
+ type: 'boolean',
255
+ default: false,
256
+ describe: 'Include the raw ProcessFlow document (large; it duplicates the extracted steps)',
234
257
  }),
235
258
  handler: wrap(async (argv, app) => {
236
259
  const identifier = await pickFlow(argv, app);
@@ -240,6 +263,7 @@ export function flowsCmd(wrap) {
240
263
  identifier,
241
264
  instanceURL: app.getEffectiveInstance(),
242
265
  depth: argv.depth,
266
+ includePayload: argv.rawPayload === true,
243
267
  });
244
268
  app.ok(inspection, {
245
269
  summary: `Flow: ${inspection.flow.name}`,
@@ -453,12 +477,53 @@ export function flowsCmd(wrap) {
453
477
  })
454
478
  .command({
455
479
  command: 'delete [identifier]',
456
- describe: 'Delete a flow (not implemented: use the Flow Designer UI)',
480
+ describe: 'Delete a flow and everything that belongs to it',
457
481
  handler: wrap(async (argv, app) => {
482
+ app.requireInstance();
458
483
  const identifier = await pickFlow(argv, app);
459
484
  if (identifier === undefined) return;
460
- throw errUsage('Flow deletion requires the Flow Designer GraphQL API - not yet implemented.\n'
461
- + 'Use the ServiceNow web UI to delete flows.');
485
+ const sysID = unwrapSysId(await resolveRecord(app.sdk, {
486
+ table: 'sys_hub_flow', identifier, matchField: 'name', resource: 'Flow',
487
+ }));
488
+ const [flow] = await app.sdk.list('sys_hub_flow', new URLSearchParams({
489
+ sysparm_query: `sys_id=${sysID}`,
490
+ sysparm_display_value: 'all',
491
+ sysparm_fields: 'sys_id,name,status,active,sys_scope',
492
+ sysparm_limit: '1',
493
+ }));
494
+ if (!flow) throw errUsage(`Flow ${identifier} (${sysID}) was not found`);
495
+ const name = getStringField(flow, 'name');
496
+ const active = getStringField(flow, 'active') === 'true';
497
+ const counted = async () => {
498
+ const counts = {};
499
+ for (const { table, query } of FLOW_OWNED_TABLES) {
500
+ counts[table] = await app.sdk.aggregateCount(table, query(sysID)).catch(() => null);
501
+ }
502
+ return counts;
503
+ };
504
+ const before = await counted();
505
+ const scopeName = getStringField(flow, 'sys_scope');
506
+ await confirmDesignerMutation(argv, app, `Delete flow "${name}" (${sysID})${active ? ', which is ACTIVE' : ''} and ${describeOwned(before)}? This cannot be undone.`);
507
+ try {
508
+ await app.sdk.delete('sys_hub_flow', sysID);
509
+ } catch (error) {
510
+ // The provider only deletes flows in the session's application scope.
511
+ if (/\b403\b|forbidden/i.test(error.message || '')) {
512
+ throw new AppError(CodeForbidden, `Flow "${name}" is in application scope ${scopeName ? `"${scopeName}"` : 'another scope'}; the provider refused the delete with HTTP 403. Switch to that scope first (jsn scopes), then retry. No delete was applied.`);
513
+ }
514
+ throw error;
515
+ }
516
+ const [stillThere] = await app.sdk.list('sys_hub_flow', new URLSearchParams({
517
+ sysparm_query: `sys_id=${sysID}`, sysparm_fields: 'sys_id', sysparm_limit: '1',
518
+ }));
519
+ if (stillThere) throw new AppError(CodeAPI, `Flow ${sysID} is still present after the delete request; nothing is reported as removed`);
520
+ const remaining = await counted();
521
+ const orphans = Object.entries(remaining).filter(([, count]) => count);
522
+ const removedText = describeOwned(before);
523
+ return app.ok({ flow: { id: sysID, name, active }, removed: before, remaining }, {
524
+ summary: `Deleted flow "${name}" (${sysID})${removedText === 'nothing' ? '' : ` with ${removedText}`}${orphans.length ? `; ${orphans.map(([table, count]) => `${count} ${table} row(s) remain`).join(', ')}` : ''}`,
525
+ breadcrumbs: [{ action: 'list', cmd: 'jsn flows list', description: 'List the remaining flows' }],
526
+ });
462
527
  }),
463
528
  })
464
529
  .epilogue('Run "jsn flows <command> --help" for details. In a terminal you can omit the target and pick\n'
@@ -26,6 +26,7 @@ export function knowledgeCmd(wrap) {
26
26
  return {
27
27
  command: 'knowledge [subcommand]', aliases: ['kb'],
28
28
  describe: 'Search and read knowledge articles through the Knowledge API',
29
+ summary: 'Search and read knowledge articles',
29
30
  handler: wrap(async (argv, app) => emit(app, argv,
30
31
  { subcommands: argv.subcommands || [], _formatted: formatCommandList({ title: 'Knowledge articles', commands: argv.subcommands || [] }) },
31
32
  'Search and read knowledge articles', [{ action: 'search', cmd: 'jsn knowledge search <text>', description: 'Find accessible articles' }])),
@@ -1,4 +1,4 @@
1
- import { formatCommandList, formatRecordForDisplay, buildQuerySuffix, buildRecordPayload, getStringField, interactiveList, resolveFieldsParam, checkDerivedFields, confirmDelete, verifyWriteBack } from '../helpers.js';
1
+ import { formatCommandList, formatRecordForDisplay, findOmittedColumns, 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
3
  import { resolveRecord, unwrapSysId } from '../resolve-record.js';
4
4
  import { errUsage } from '../errors.js';
@@ -83,6 +83,7 @@ export function recordsCmd(wrap) {
83
83
  return {
84
84
  command: 'records [subcommand]',
85
85
  describe: 'Query and manage records in any table (e.g. "records list --table incident --query priority=1")',
86
+ summary: 'Query any table when no specialized command fits',
86
87
  builder: (yargs) => {
87
88
  return yargs
88
89
  .command({
@@ -149,7 +150,9 @@ export function recordsCmd(wrap) {
149
150
  const fields = resolveFieldsParam(columns);
150
151
  const params = recordListParams({ limit: argv['sys-id'] ? 1 : argv.limit, offset: argv.offset, fields, query });
151
152
  const records = await listRecords(app.sdk, { table, params, displayValues: argv.displayValues });
152
- const displayRecords = fields && !argv.displayValues ? records.map(r => formatRecordForDisplay(r, columns)) : records;
153
+ const missingColumns = fields ? findOmittedColumns(records, columns) : [];
154
+ const presentColumns = missingColumns.length ? columns.filter(c => !missingColumns.includes(c)) : columns;
155
+ const displayRecords = fields && !argv.displayValues ? records.map(r => formatRecordForDisplay(r, presentColumns)) : records;
153
156
 
154
157
  // include_counts: default opt-in on every list. Opt out per-profile
155
158
  // (config include_counts:false) or per-invocation (--no-count).
@@ -190,8 +193,14 @@ export function recordsCmd(wrap) {
190
193
  table,
191
194
  count: records.length,
192
195
  columns,
196
+ ...(missingColumns.length ? {
197
+ missing_columns: missingColumns,
198
+ warnings: [
199
+ `Column(s) not returned by ServiceNow (non-existent or restricted on ${table}): ${missingColumns.join(', ')}. Run \`jsn columns --table ${table}\` to inspect valid fields.`,
200
+ ],
201
+ } : {}),
193
202
  records: displayRecords,
194
- pagination: { limit: argv.limit, offset: argv.offset, ...(total != null ? { total } : {}) },
203
+ pagination: { limit: argv.limit, offset: argv.offset, ...(total != null ? { total, hasMore: argv.offset + argv.limit < total } : {}) },
195
204
  context: { instance_url: app.getEffectiveInstance() },
196
205
  }, {
197
206
  summary: `${records.length} record(s) from ${table}${total != null ? ` of ${total}` : ''}`,
@@ -1,4 +1,5 @@
1
- import { configureGlobalDefaults, configureDocumentation } from '../setup-preferences.js';
1
+ import { configureGlobalDefaults, configureDocumentation, connectionPreferences } from '../setup-preferences.js';
2
+ import { saveConfig } from '../config.js';
2
3
  import { select } from '../prompts.js';
3
4
  import { loginWizard, loginProfile, showAuthStatus, switchProfile, modifyProfile, logoutProfile, removeConnection } from './auth.js';
4
5
  import { errUsageHint } from '../errors.js';
@@ -37,6 +38,7 @@ const setupHelp = () => [
37
38
  'Use --no-read-only, --no-confirm-deletes, --no-include-counts or --no-make-default for the opposite value.',
38
39
  'Use --json for structured output. Explicit flags avoid implicit pickers; ambiguous targets return an error.',
39
40
  'Discover all options with jsn auth <command> --help.',
41
+ 'Configure settings directly: jsn setup --configure-defaults or jsn setup --configure-docs.',
40
42
  ].join('\n');
41
43
 
42
44
  /** The setup hub prompt; q and Escape resolve with no selected action. */
@@ -87,7 +89,7 @@ export async function authHubMenu({ promptFn = authHubPrompt, input, output, has
87
89
  */
88
90
  export async function dispatchSetupAction(app, argv, action) {
89
91
  if (action === 'add') {
90
- return loginWizard(app, argv);
92
+ return loginWizard(app, argv, { concise: true });
91
93
  } else if (action === 'login') {
92
94
  return loginProfile(argv, app);
93
95
  } else if (action === 'status') {
@@ -119,30 +121,40 @@ export function setupCmd(wrap) {
119
121
  return {
120
122
  command: 'setup',
121
123
  describe: 'Set up JSN defaults and manage ServiceNow connections (interactive)',
122
- builder: y => y.option('docs-source', { type: 'string', choices: ['snapshot', 'github', 'skip'], describe: 'Install optional documentation directly without the authentication wizard' }).epilogue(setupHelp()),
124
+ summary: 'Connect to ServiceNow and manage profiles',
125
+ builder: y => y.option('docs-source', { type: 'string', choices: ['snapshot', 'github', 'skip'], describe: 'Install optional documentation directly without the authentication wizard' })
126
+ .option('configure-defaults', { type: 'boolean', describe: 'Configure defaults for future connections without the hub' })
127
+ .option('configure-docs', { type: 'boolean', describe: 'Configure documentation without the hub' }).epilogue(setupHelp()),
123
128
  handler: wrap(async (argv, app) => {
124
129
  if (argv['docs-source']) {
125
130
  const { installDocumentation } = await import('./docs/install.js');
126
131
  app.ok(await installDocumentation(argv['docs-source']));
127
132
  return;
128
133
  }
134
+ if (argv['configure-defaults'] || argv['configure-docs']) {
135
+ if (argv['configure-defaults']) await configureGlobalDefaults(app.config, { documentation: false });
136
+ if (argv['configure-docs']) await configureDocumentation(app.config);
137
+ app.ok({ settings: true }, { summary: 'Settings saved; existing connections unchanged' });
138
+ return;
139
+ }
129
140
  const { canUsePicker } = await import('../helpers.js');
130
141
  if (!app.isInteractive() || !canUsePicker(app, argv)) {
131
142
  throw errUsageHint('"jsn setup" is interactive. Use explicit auth commands instead.', setupHelp());
132
143
  }
133
144
  const profileNames = Object.keys(app.config.profiles || {});
134
145
  const firstSetup = !app.config.connectionDefaults;
135
- if (firstSetup) await configureGlobalDefaults(app.config);
136
- else if (!app.config.docs) await configureDocumentation(app.config);
146
+ if (firstSetup) {
147
+ app.config.connectionDefaults = connectionPreferences(app.config);
148
+ await saveConfig(app.config);
149
+ }
137
150
  if (profileNames.length === 0 && firstSetup) {
138
- const result = await loginWizard(app, argv);
139
- await showAuthStatus({ ...argv, profile: result.profileName }, app);
151
+ await loginWizard(app, argv, { concise: true });
140
152
  return;
141
153
  }
142
154
  const action = await authHubMenu({ hasProfiles: profileNames.length > 0 });
143
155
  if (action === undefined) return;
144
156
  const result = await dispatchSetupAction(app, argv, action);
145
- if (!['status', 'advanced'].includes(action)) await showAuthStatus({ ...argv, profile: result?.profile || result?.profileName }, app);
157
+ if (!['add', 'status', 'advanced'].includes(action)) await showAuthStatus({ ...argv, profile: result?.profile || result?.profileName }, app);
146
158
  }),
147
159
  };
148
160
  }
@@ -1,5 +1,5 @@
1
1
  import { enrichRelatedLists, relatedListOptions } from '../related-lists.js';
2
- import { formatRecordForDisplay, getStringField, buildQuerySuffix, resolveFieldsParam, buildRecordPayload, confirmDelete } from '../helpers.js';
2
+ import { formatRecordForDisplay, findOmittedColumns, getStringField, buildQuerySuffix, resolveFieldsParam, buildRecordPayload, confirmDelete } from '../helpers.js';
3
3
  import { getRecord, listRecords, recordListParams, createRecord, updateRecord, deleteRecord, recordOptions } from '../records-engine.js';
4
4
  import { resolveSysId } from '../resolve-record.js';
5
5
  import { declareCapabilities } from '../capabilities.js';
@@ -28,7 +28,9 @@ export function ticketsCmd(wrap) {
28
28
  const q = argv.query ? argv.query + '^ORDERBYDESCsys_updated_on' : 'ORDERBYDESCsys_updated_on';
29
29
  const params = recordListParams({ limit: argv.limit, offset: argv.offset, fields, query: q });
30
30
  const records = await listRecords(app.sdk, { table: 'task', params, displayValues: argv.displayValues });
31
- const displayRecords = fields && !argv.displayValues ? records.map(r => formatRecordForDisplay(r, columns)) : records;
31
+ const missingColumns = fields ? findOmittedColumns(records, columns) : [];
32
+ const presentColumns = missingColumns.length ? columns.filter(c => !missingColumns.includes(c)) : columns;
33
+ const displayRecords = fields && !argv.displayValues ? records.map(r => formatRecordForDisplay(r, presentColumns)) : records;
32
34
  const breadcrumbs = [
33
35
  { action: 'create', cmd: 'jsn tickets create -f short_description=New ticket', description: 'Create a new ticket' },
34
36
  ];
@@ -50,8 +52,14 @@ export function ticketsCmd(wrap) {
50
52
  table: 'task',
51
53
  count: records.length,
52
54
  columns,
55
+ ...(missingColumns.length ? {
56
+ missing_columns: missingColumns,
57
+ warnings: [
58
+ `Column(s) not returned by ServiceNow (non-existent or restricted on task): ${missingColumns.join(', ')}. Run \`jsn columns --table task\` to inspect valid fields.`,
59
+ ],
60
+ } : {}),
53
61
  records: displayRecords,
54
- pagination: { limit: argv.limit, offset: argv.offset },
62
+ pagination: { limit: argv.limit, offset: argv.offset, hasMore: records.length === argv.limit },
55
63
  context: { instance_url: app.getEffectiveInstance() },
56
64
  }, { summary: `${records.length} ticket(s)`, breadcrumbs });
57
65
  }),
package/src/errors.js CHANGED
@@ -3,6 +3,28 @@
3
3
  export const CodeUsage = 'usage_error';
4
4
  export const CodeNotFound = 'not_found';
5
5
  export const CodeAuth = 'auth_error';
6
+ export const CodeMfaRequired = 'mfa_required';
7
+ export const CodeMfaRejected = 'mfa_code_rejected';
8
+
9
+ // These errors are terminal for the invocation and precede operation dispatch.
10
+ export function errMfaRequired() {
11
+ const error = new AppError(CodeMfaRequired,
12
+ 'Multi-factor authentication requires a six-digit authenticator code.',
13
+ 'Re-run in an interactive terminal without --json/--get, or explicitly configure OAuth or a browser session with jsn auth login. JSN never stores TOTP seeds or generates codes.');
14
+ error.notSent = true;
15
+ return error;
16
+ }
17
+
18
+ export function errMfaRejected() {
19
+ const error = new AppError(CodeMfaRejected, 'MFA verification could not establish the selected authenticated session.',
20
+ 'The challenge failed, expired, or could not be verified. Re-run the command to start a new challenge.');
21
+ error.notSent = true;
22
+ return error;
23
+ }
24
+
25
+ export function isTerminalAuthError(error) {
26
+ return error?.name === 'PromptCancelled' || error?.code === CodeMfaRequired || error?.code === CodeMfaRejected;
27
+ }
6
28
  export const CodeForbidden = 'forbidden';
7
29
  export const CodeRateLimit = 'rate_limited';
8
30
  export const CodeNetwork = 'network_error';
@@ -237,7 +259,7 @@ export function renderAppError(err, { app = null, argv = null, identifier = '' }
237
259
  if (err.name === 'PromptCancelled') return { stream: 'stderr', text: 'Cancelled.\n', exitCode: 0 };
238
260
  const code = err.code || 'unknown';
239
261
 
240
- if (code === CodeAuth) {
262
+ if (code === CodeAuth || code === CodeMfaRequired || code === CodeMfaRejected) {
241
263
  if (resolveJsonMode(app, argv) && app) return { stream: 'stdout', text: null, exitCode: 1, appErr: true };
242
264
  let text = `Error (auth): ${err.message}\n`;
243
265
  if (err.hint) text += `\nHint: ${err.hint}\n`;