@jacebenson/jsn 5.5.3-dev.182.1 → 5.5.3-dev.183.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.5.3-dev.182.1",
3
+ "version": "5.5.3-dev.183.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": {
@@ -28,6 +28,7 @@
28
28
  "@inquirer/core": "^10.3.2",
29
29
  "@inquirer/prompts": "^7.10.1",
30
30
  "better-sqlite3": "^13.1.1",
31
+ "commonmark": "^0.31.2",
31
32
  "js-yaml": "^5.5.0",
32
33
  "saxes": "^6.0.0",
33
34
  "turndown": "^7.2.5"
@@ -1,5 +1,6 @@
1
1
  // Public documentation service. Deliberately independent of instance credentials.
2
2
  import { AppError } from '../../errors.js';
3
+ import { selectDocument, SECTION_PROTOCOL } from './sections.js';
3
4
 
4
5
  export const DEFAULT_DOCS_URL = 'https://jsn.jace.pro';
5
6
  const MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
@@ -73,12 +74,27 @@ export async function searchHostedDocs(options = {}) {
73
74
  export async function getHostedDoc(idOrPath, options = {}) {
74
75
  const identifier = String(idOrPath || '');
75
76
  if (!identifier) throw new AppError('usage_error', 'Provide a document ID or exact path.');
77
+ if ((options.outline && options.section !== undefined) || (options.section !== undefined && !String(options.section).trim())) throw new AppError('usage_error', 'Use either --outline or one nonempty --section.');
76
78
  const numeric = /^\d+$/.test(identifier);
77
79
  const { data, service } = await request(numeric ? `api/docs/${identifier}` : 'api/docs/document', {
78
80
  ...(numeric ? {} : { path: identifier }), revision: options.revision, release: options.release,
81
+ outline: options.outline || undefined, section: options.section,
79
82
  }, options);
80
- if (!data || !data.document || typeof data.document.body !== 'string' || typeof data.document.path !== 'string' || typeof data.revision !== 'string') throw invalidResponse();
81
- return { ...data.document, release: options.release ?? data.release, revision: data.revision, service };
83
+ const targeted = options.outline || options.section !== undefined;
84
+ const native = data?.section_protocol === SECTION_PROTOCOL;
85
+ if (!data?.document || typeof data.document.path !== 'string' || typeof data.revision !== 'string' ||
86
+ (!(targeted && native && options.outline) && typeof data.document.body !== 'string')) throw invalidResponse();
87
+ if (options.revision && data.revision !== options.revision) throw new AppError('api_error', 'Documentation revision mismatch. Refresh the outline.');
88
+ if (options.release && data.document.release && data.document.release !== options.release) throw new AppError('api_error', `Documentation service returned release ${data.document.release}, expected ${options.release}.`);
89
+ let row = { ...data.document, release: options.release ?? data.release ?? data.document.release, revision: data.revision, service };
90
+ if (targeted) {
91
+ if (!native) row = selectDocument(row, options);
92
+ const mode = options.outline ? 'outline' : 'section';
93
+ if (row.retrieval?.protocol !== SECTION_PROTOCOL || row.retrieval?.mode !== mode ||
94
+ (options.outline ? !Array.isArray(row.outline) : !row.section || row.retrieval.subtree_complete !== true)) throw invalidResponse();
95
+ row.retrieval = { ...row.retrieval, execution: native ? 'service' : 'client-fallback', full_document_transferred: !native };
96
+ }
97
+ return row;
82
98
  }
83
99
  export async function getHostedDocsStatus(options = {}) {
84
100
  const { data, service } = await request('api/docs/status', { release: options.release }, options);
@@ -9,6 +9,10 @@ import { listDocsReleases } from './releases.js';
9
9
 
10
10
  declareCapabilities('docs', { noInstance: true, skipDailyChecks: true });
11
11
 
12
+ function presented(data, text) {
13
+ return Object.defineProperty(data, '_formatted', { value: text, enumerable: false });
14
+ }
15
+
12
16
  async function search(argv, app) {
13
17
  const query = Array.isArray(argv.query) ? argv.query.join(' ') : argv.query;
14
18
  const result = await searchHostedDocs({ query, limit: argv.limit, offset: argv.offset, bundle: argv.bundle, release: resolveDocsRelease(argv.release, app.config), serviceUrl: await documentationService(app.config, resolveDocsRelease(argv.release, app.config)) });
@@ -29,11 +33,18 @@ async function search(argv, app) {
29
33
  async function read(argv, app) {
30
34
  const maxLines = argv.lines ?? 80;
31
35
  if (!Number.isInteger(maxLines) || maxLines < 1 || maxLines > 10000) throw new AppError('usage_error', 'Use --lines 1–10000.');
32
- const row = await getHostedDoc(argv.path || argv['id-or-path'], { revision: argv.revision, release: resolveDocsRelease(argv.release, app.config), serviceUrl: await documentationService(app.config, resolveDocsRelease(argv.release, app.config)) });
36
+ const row = await getHostedDoc(argv.path || argv['id-or-path'], { outline: argv.outline, section: argv.section, revision: argv.revision, release: resolveDocsRelease(argv.release, app.config), serviceUrl: await documentationService(app.config, resolveDocsRelease(argv.release, app.config)) });
33
37
  const title = row.title || row.path;
38
+ const provenance = `${row.path}\nRelease: ${row.release} | Revision: ${row.revision}\nService: ${row.service}`;
39
+ if (row.outline) {
40
+ const text = row.outline.map(h => `${' '.repeat(h.ancestors.length)}${h.title} [lines ${h.start_line}–${h.end_line}]\n${' '.repeat(h.ancestors.length)} ${h.id}`).join('\n');
41
+ return app.ok(presented(row, `${title}\n${provenance}\n\n${text || 'No selectable headings.'}\n\nUse --section '<ID>' with this --path. Selection includes preamble and ancestor introductions.\nOther sections and linked prerequisites may still matter.\nRetrieval: ${row.retrieval.execution}; full document transferred: ${row.retrieval.full_document_transferred}\n`));
42
+ }
34
43
  const lines = row.body.split('\n');
35
44
  const hint = lines.length > maxLines ? `\n\n… ${lines.length - maxLines} more lines (use --lines ${Math.min(lines.length, 10000)} or --json for full content)` : '';
36
- app.ok({ ...row, _formatted: `Doc ${row.id}: ${title} in ${row.release}\n${'─'.repeat(Math.min(title.length, 80))}\n\n${lines.slice(0, maxLines).join('\n')}${hint}\n` }, { summary: `Doc ${row.id}: ${title} in ${row.release}` });
45
+ const content = row.section ? row.body : lines.slice(0, maxLines).join('\n') + hint;
46
+ const context = row.section ? `\nComplete selected subtree: ${row.section.title}\n${row.retrieval.context_policy}\nOther sections to check: ${row.retrieval.context_sections.map(h => h.title).join('; ') || 'none'}.\nUse --outline to retrieve their IDs.\nSemantic answer completeness: unknown. Retrieval: ${row.retrieval.execution}.\n` : '';
47
+ app.ok(presented(row, `Doc ${row.id}: ${title} in ${row.release}\n${provenance}${context}\n${content}\n`), { summary: `Doc ${row.id}: ${title} in ${row.release}` });
37
48
  }
38
49
 
39
50
  export function docsCmd(wrap) {
@@ -53,7 +64,9 @@ export function docsCmd(wrap) {
53
64
  .option('bundle', { type: 'string', describe: 'Filter by documentation bundle' })
54
65
  .option('path', { type: 'string', describe: 'Read an exact document path or ID from search results' })
55
66
  .option('revision', { type: 'string', describe: 'Require the revision returned by search (recommended with IDs)' })
56
- .option('lines', { type: 'number', default: 80, describe: 'Preview lines; JSON contains the full Markdown body' })
67
+ .option('outline', { type: 'boolean', describe: 'List revision-bound section IDs for --path, without document body' })
68
+ .option('section', { type: 'string', describe: 'Read a complete subtree by outline ID or exact unique heading; includes ancestor introductions' })
69
+ .option('lines', { type: 'number', default: 80, describe: 'Full-document human preview lines; JSON and selected sections are not truncated' })
57
70
  .command({ command: 'releases', describe: 'List locally installed documentation families', handler: wrap(async (_argv, app) => {
58
71
  const releases = listDocsReleases();
59
72
  app.ok({ releases, _formatted: releases.length ? releases.map(row => `${row.release}${row.default ? ' (default)' : ''} ${row.revision || 'unknown'} ${row.documents} documents ${row.indexPath}`).join('\n') + '\n' : 'No local documentation families installed.\n' }, { summary: `${releases.length} local documentation release(s)` });
@@ -90,6 +103,7 @@ export function docsCmd(wrap) {
90
103
  for (const signal of ['SIGINT', 'SIGTERM']) process.once(signal, () => server.close());
91
104
  return;
92
105
  }
106
+ if ((argv.outline || argv.section !== undefined) && !argv.path) throw new AppError('usage_error', 'Use --path with --outline or --section.');
93
107
  if (argv.path) return read(argv, app);
94
108
  if (argv.query?.length) return search(argv, app);
95
109
  const service = await documentationService(app.config, resolveDocsRelease(argv.release, app.config));
@@ -1,5 +1,6 @@
1
1
  // One search engine for the hosted website and the optional local service.
2
2
  import fs from 'node:fs';
3
+ import { selectDocument } from './sections.js';
3
4
  import path from 'node:path';
4
5
  import Database from 'better-sqlite3';
5
6
  import { resolveDocsDbPath } from './db.js';
@@ -72,11 +73,11 @@ export class DocumentationIndex {
72
73
  .all(...binds, text, text, text, limit, offset).map(documentationSummary);
73
74
  return { query: text, revision: this.revision(), total, count: results.length, limit, offset, results };
74
75
  }
75
- document({ id, path: docPath } = {}) {
76
+ document({ id, path: docPath, outline = false, section } = {}) {
76
77
  const select = 'SELECT id, path, title, bundle, doc_type, release, body FROM docs WHERE';
77
78
  const row = docPath ? this.db.prepare(`${select} path = ?`).get(docPath)
78
79
  : /^\d{1,18}$/.test(String(id)) ? this.db.prepare(`${select} id = ?`).get(String(id)) : null;
79
80
  if (!row) throw new DocumentationError('Document not found.', 404);
80
- return row;
81
+ return outline || section !== undefined ? selectDocument({ ...row, revision: this.revision() }, { outline, section }) : row;
81
82
  }
82
83
  }
@@ -0,0 +1,59 @@
1
+ // CommonMark source positions let us slice original text, never reserialize tables/code.
2
+ import * as commonmark from 'commonmark';
3
+ import { createHash } from 'node:crypto';
4
+ import { AppError } from '../../errors.js';
5
+
6
+ export const SECTION_PROTOCOL = 'sections-v1';
7
+ function failure(message) { return new AppError('usage_error', message, 'Use --outline for exact titles and revision-bound IDs.', 400); }
8
+ export function selectDocument(row, { outline = false, section } = {}) {
9
+ if (outline && section !== undefined) throw failure('Use either --outline or --section, not both.');
10
+ if (section !== undefined && !String(section).trim()) throw failure('Section must not be empty.');
11
+ if (!outline && section === undefined) return row;
12
+ const body = row.body;
13
+ const starts = [0];
14
+ for (const match of body.matchAll(/\r\n|\n|\r/g)) starts.push(match.index + match[0].length);
15
+ const ast = new commonmark.Parser().parse(body);
16
+ const headings = [];
17
+ for (let node = ast.firstChild; node; node = node.next) {
18
+ if (node.type !== 'heading') continue; // Never split lists, blockquotes or HTML blocks.
19
+ let title = '', walker = node.walker(), event;
20
+ while ((event = walker.next())) {
21
+ if (event.entering && ['text', 'code'].includes(event.node.type)) title += event.node.literal;
22
+ if (event.entering && ['softbreak', 'linebreak'].includes(event.node.type)) title += ' ';
23
+ }
24
+ headings.push({ title, depth: node.level, start_line: node.sourcepos[0][0], start: starts[node.sourcepos[0][0] - 1] });
25
+ }
26
+ const identity = createHash('sha256').update(JSON.stringify([SECTION_PROTOCOL, row.path, row.release, row.revision, body])).digest('hex').slice(0, 24);
27
+ const stack = [];
28
+ for (let i = 0; i < headings.length; i++) {
29
+ const h = headings[i];
30
+ while (stack.length && headings[stack.at(-1)].depth >= h.depth) stack.pop();
31
+ h.ancestors = stack.map(n => headings[n].id);
32
+ h.id = `s1:${identity}:${i + 1}`;
33
+ const next = headings.slice(i + 1).find(n => n.depth <= h.depth);
34
+ h.end = next?.start ?? body.length;
35
+ h.end_line = next ? next.start_line - 1 : starts.length;
36
+ h.introEnd = headings[i + 1]?.start ?? body.length;
37
+ stack.push(i);
38
+ }
39
+ const publicHeading = ({ start: _start, end: _end, introEnd: _introEnd, ...h }) => h; // Offsets remain an implementation detail.
40
+ const metadata = { protocol: SECTION_PROTOCOL, document_complete: false, semantic_completeness: 'unknown', truncated: false,
41
+ heading_policy: 'CommonMark top-level ATX/setext; container and HTML headings are not boundaries' };
42
+ const { body: _body, ...identityRow } = row;
43
+ if (outline) return { ...identityRow, outline: headings.map(publicHeading), retrieval: { ...metadata, mode: 'outline', total_lines: starts.length, context_policy: 'Selection includes preamble and ancestor introductions; other sections may contain relevant context.' } };
44
+ const matches = headings.filter(h => h.id === section || h.title === section);
45
+ if (!matches.length) throw failure('No matching section. IDs are document- and revision-bound; refresh the outline.');
46
+ if (matches.length !== 1) throw failure(`Ambiguous section ${JSON.stringify(section)}. Choose an ID: ${matches.map(h => `${h.id} (${h.title}, line ${h.start_line})`).join('; ')}`);
47
+ const h = matches[0];
48
+ const spans = [];
49
+ const add = (start, end, kind) => { if (end > start) spans.push({ start, end, kind }); };
50
+ add(0, headings[0]?.start ?? body.length, 'preamble');
51
+ for (const id of h.ancestors) { const a = headings.find(n => n.id === id); add(a.start, a.introEnd, 'ancestor-introduction'); }
52
+ add(h.start, h.end, 'section-subtree');
53
+ return { ...identityRow, body: spans.map(s => body.slice(s.start, s.end)).join(''), section: publicHeading(h), retrieval: {
54
+ ...metadata, mode: 'section', subtree_complete: true, document_complete: spans.reduce((n, s) => n + s.end - s.start, 0) === body.length,
55
+ context_policy: 'Preamble and ancestor introductions included. Sibling sections and linked prerequisites are not automatically included; read the full document when needed.',
56
+ context_sections: headings.filter(n => !spans.some(s => n.start >= s.start && n.start < s.end)).map(n => ({ id: n.id, title: n.title })),
57
+ included_spans: spans.map(s => ({ start_offset: s.start, end_offset: s.end, kind: s.kind })),
58
+ } };
59
+ }
@@ -1,4 +1,5 @@
1
1
  import http from 'node:http';
2
+ import { SECTION_PROTOCOL } from './sections.js';
2
3
  import fs from 'node:fs';
3
4
  import path from 'node:path';
4
5
  import os from 'node:os';
@@ -27,7 +28,9 @@ export async function startDocumentationServer({ storage = serviceStorage(), hos
27
28
  if (url.pathname === '/api/docs/search') return send(200, { ...index.search({ query: params.q, limit: params.limit ?? 20, offset: params.offset ?? 0, bundle: params.bundle }), release });
28
29
  const revision = index.revision();
29
30
  if (params.revision && params.revision !== revision) return send(409, { error: 'Documentation has changed. Search again or retrieve by exact path.' });
30
- return send(200, { release, revision, document: index.document({ path: params.path, id: url.pathname.split('/').at(-1) }) });
31
+ if (params.outline !== undefined && params.outline !== 'true') return send(400, { error: 'outline must be true.' });
32
+ const document = index.document({ path: params.path, id: url.pathname.split('/').at(-1), outline: params.outline === 'true', section: params.section });
33
+ return send(200, { release, revision, section_protocol: SECTION_PROTOCOL, document });
31
34
  } catch (error) { send(error.status || 503, { error: error.status ? error.message : 'Documentation search is temporarily unavailable.' }); }
32
35
  finally { index?.close(); }
33
36
  });