@jacebenson/jsn 4.5.1-dev.117.1 → 4.5.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
@@ -11,7 +11,7 @@ npm install -g @jacebenson/jsn
11
11
  jsn setup
12
12
  ```
13
13
 
14
- See the [setup guide](https://github.com/jacebenson/jsn/blob/main/docs/docs-setup.md) to connect an instance safely.
14
+ See the [setup guide](docs/docs-setup.md) to connect an instance safely.
15
15
 
16
16
  ### Dev channel
17
17
 
@@ -121,7 +121,7 @@ jsn records list --table incident --limit 10 --json
121
121
  jsn flows list
122
122
  ```
123
123
 
124
- Run `jsn --help` for the command list. See the [CLI guide](https://github.com/jacebenson/jsn/blob/main/docs/cli-guide.md) for authentication, output formats, development, and examples. The [docs site](https://jacebenson.github.io/jsn/) has feature guides.
124
+ Run `jsn --help` for the command list. See the [CLI guide](docs/cli-guide.md) for authentication, output formats, development, and examples. The [docs site](https://jacebenson.github.io/jsn/) has feature guides.
125
125
 
126
126
  ## AI agents
127
127
 
@@ -130,8 +130,7 @@ JSN includes a skill for Claude Code, OpenCode, Hermes, Cursor, Copilot, and oth
130
130
  ## Development
131
131
 
132
132
  ```bash
133
- cd cli
134
- npm ci
133
+ npm install
135
134
  npm test
136
135
  ```
137
136
 
@@ -207,32 +206,3 @@ requests. Save the original domain ID from `session-current` if you intend to
207
206
  restore it afterward. A failed readback can leave the session changed; inspect
208
207
  `session-current` before retrying. These commands do not call `touch-session`.
209
208
  Other authentication methods retain the existing profile configuration flow.
210
-
211
- ## Documentation search
212
-
213
- ```bash
214
- jsn docs "GlideRecord" --limit 5
215
- jsn docs --path "api-reference/c_GlideRecordClientSideAPI.md"
216
- ```
217
-
218
- No ServiceNow connection is required. Hosted docs at `https://jsn.jace.pro` are
219
- the default and download no database. `jsn setup` asks once for defaults for new
220
- connections and whether to use hosted documentation. Decline hosted docs to let
221
- JSN start a local server, or decline that too and enter your own service base URL.
222
- Later changes live under **Advanced settings** in setup. Existing connections
223
- keep their saved settings.
224
-
225
- Local mode downloads the public documentation on first use and checks for updates
226
- daily while running. The server starts again automatically when needed. A first
227
- search can report that the index is still being prepared; later updates preserve
228
- the last working index if offline. Local storage lives under
229
- `~/.jsn/docs-service` (`JSN_DATA_HOME` overrides the parent directory).
230
-
231
- To host the same service yourself, run `jsn docs --serve --host 0.0.0.0 --port 3000`.
232
- It manages its own index; expose it through your normal HTTPS proxy. The hosted
233
- website and this server share one search engine. `JSN_DOCS_URL` temporarily
234
- overrides the saved choice without starting a local server.
235
-
236
- Exact paths remain stable across revisions. Numeric IDs can be pinned with
237
- `--revision <search-revision>`. Older `docs search`, `docs show` and `docs status`
238
- spellings remain compatible but are omitted from the everyday help menu.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jacebenson/jsn",
3
- "version": "4.5.1-dev.117.1",
3
+ "version": "4.5.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": {
@@ -12,8 +12,8 @@
12
12
  "test:mutation": "stryker run",
13
13
  "lint": "npx eslint src/ bin/ test/",
14
14
  "start": "node bin/jsn.js",
15
- "docs": "npm --prefix ../docs run build",
16
- "docs:serve": "npm --prefix ../docs run serve"
15
+ "docs": "npm --prefix docs run build",
16
+ "docs:serve": "npm --prefix docs run serve"
17
17
  },
18
18
  "keywords": [
19
19
  "servicenow",
@@ -31,6 +31,3 @@ For development:
31
31
  For incoming update sets: import the XML, preview the set, and resolve preview
32
32
  errors with the human where needed. Once the preview is clear, commit the set
33
33
  and verify the results.
34
-
35
- Search documentation with `jsn docs "query"` or read with `jsn docs --path <path>`.
36
- Documentation source and defaults for future connections are configured in `jsn setup`.
@@ -12,7 +12,7 @@ const names = (x) => typeof x === 'string' ? [x] : (x || []);
12
12
  */
13
13
  const isArrayOption = (spec) => spec?.type === 'array' || spec?.array === true;
14
14
  const commandName = (command) => command.trim().split(/\s+/)[0];
15
- const positionSpec = (command) => [...command.matchAll(/([<[])([^>\]]+)[>\]]/g)].map((m) => ({ name: m[2].replace(/\.\.$/, ''), array: m[2].endsWith('..'), required: m[1] === '<' }));
15
+ const positionSpec = (command) => [...command.matchAll(/([<[])([^>\]]+)[>\]]/g)].map((m) => ({ name: m[2], required: m[1] === '<' }));
16
16
 
17
17
  class CommandNode {
18
18
  constructor(definition) {
@@ -286,7 +286,7 @@ export class LocalCLI {
286
286
  * parent's children are only registered when its builder is invoked.
287
287
  */
288
288
  commandRegistry() {
289
- const visible = (node) => node.name !== this.completionCommand && !node.definition.hidden;
289
+ const visible = (node) => node.name !== this.completionCommand;
290
290
  const serialize = (node) => {
291
291
  node.build();
292
292
  return {
@@ -319,7 +319,7 @@ export class LocalCLI {
319
319
  /** Structured child signatures for a parent node, built on demand. */
320
320
  subcommandsOf(node) {
321
321
  return node.children
322
- .filter((child) => child.name !== this.completionCommand && !child.definition.hidden)
322
+ .filter((child) => child.name !== this.completionCommand)
323
323
  .map((child) => {
324
324
  child.build();
325
325
  return {
@@ -338,8 +338,7 @@ export class LocalCLI {
338
338
  }
339
339
  const lines = [node.usageText || `Usage: ${this.script} ${path.join(' ') || '<command>'}`];
340
340
  if (node.definition.describe) lines.push(`\n${node.definition.describe}`);
341
- const children = node.children.filter(n => n.name !== this.completionCommand && !n.definition.hidden);
342
- if (children.length) lines.push('\nCommands:\n' + children.map((n) => ` ${n.definition.command} ${n.definition.describe || ''}`).join('\n'));
341
+ if (node.children.length) lines.push('\nCommands:\n' + node.children.filter((n) => n.name !== this.completionCommand).map((n) => ` ${n.definition.command} ${n.definition.describe || ''}`).join('\n'));
343
342
  if (node.options.size) lines.push('\nOptions:\n' + [...node.options].map(([name, s]) => ` --${name}${s.alias ? `, -${names(s.alias).join(', -')}` : ''} ${s.describe || s.description || ''}`).join('\n'));
344
343
  if (node.epilogueText) lines.push(`\n${node.epilogueText}`);
345
344
  process.stdout.write(lines.join('\n') + '\n');
@@ -354,7 +353,7 @@ export class LocalCLI {
354
353
  node.build();
355
354
  const argv = { _: path.map((n) => n.name) };
356
355
  const completionFilter = (callback) => {
357
- const values = [...node.children].filter((n) => n.name !== this.completionCommand && !n.definition.hidden)
356
+ const values = [...node.children].filter((n) => n.name !== this.completionCommand)
358
357
  .flatMap((n) => path.length ? [n.name] : [n.name, ...n.aliases]);
359
358
  const opts = [...this._optionConfig(path)].map(([name]) => `--${name}`);
360
359
  callback(null, [...new Set([...values, ...opts])]);
@@ -386,7 +385,7 @@ export class LocalCLI {
386
385
  return this._fail(`Unknown command: ${firstWord}`);
387
386
  }
388
387
  if (this.strictCmd && path.length && node.children.length && firstWord
389
- && !node.definition.defaultPositionals && !this._lookup(node.children, firstWord)) {
388
+ && !this._lookup(node.children, firstWord)) {
390
389
  return this._fail(`Unknown command: ${firstWord}`);
391
390
  }
392
391
  if (!path.length && this.root.demand) return this._fail(this.root.demand.message);
@@ -402,14 +401,7 @@ export class LocalCLI {
402
401
  const positions = positionSpec(node.definition.command || '').map((position) => ({
403
402
  ...position, ...node.positionals.get(position.name), name: position.name,
404
403
  }));
405
- let positionalIndex = 0;
406
- for (const position of positions) {
407
- if (position.array) {
408
- const values = parsed.positionals.slice(positionalIndex);
409
- if (values.length) argv[position.name] = values;
410
- positionalIndex = parsed.positionals.length;
411
- } else if (parsed.positionals[positionalIndex] !== undefined) argv[position.name] = parsed.positionals[positionalIndex++];
412
- }
404
+ parsed.positionals.forEach((value, i) => { if (positions[i]) argv[positions[i].name] = value; });
413
405
  for (const spec of specs) if (spec.demandOption && argv[spec.name] === undefined) return this._fail(`Missing required argument: --${spec.name}`);
414
406
  for (const pos of positions) if (pos.required && argv[pos.name] === undefined) return this._fail(`Missing required argument: ${pos.name}`);
415
407
  for (const middleware of this.middlewares) await middleware(argv);
@@ -1,4 +1,3 @@
1
- import { connectionPreferences, chooseConnectionPreferences } from '../setup-preferences.js';
2
1
  import { detectCommandAudience } from '../command-audience.js';
3
2
  import { getEffectiveInstance, normalizeInstanceURL, saveConfig, setActiveProfile } from '../config.js';
4
3
  import { errUsage, errUsageHint, errConfirmationRequired } from '../errors.js';
@@ -327,7 +326,7 @@ export async function loginWizard(app, argv = {}) {
327
326
  const username = await input({ message: 'Username:', validate: value => value.trim() ? true : 'A username is required' });
328
327
  request._basicCredentials = { username: username.trim(), password: await password({ message: 'Password:' }) };
329
328
  }
330
- const settings = await chooseConnectionPreferences(app.config, profileSettingValues(argv), { confirm });
329
+ const settings = await configureProfileOptions({}, argv, { interactive: true });
331
330
  request['read-only'] = settings.read_only;
332
331
  request['skip-confirmations'] = settings.skip_confirmations;
333
332
  request['include-counts'] = settings.include_counts;
@@ -621,10 +620,9 @@ Find your instance URL in your browser's address bar when logged into ServiceNow
621
620
  throw errUsage('OAuth login requires --print-url followed by --code <code> when noninteractive.');
622
621
  }
623
622
  const preliminary = argv.printUrl && !argv.waitFile;
624
- const explicitPreferences = ['read-only', 'skip-confirmations', 'include-counts'].every(flag => typeof argv[flag] === 'boolean');
625
- const preferences = !targetProfile && interactive && !preliminary && !explicitPreferences
626
- ? await chooseConnectionPreferences(app.config, argv, { confirm: (await import('../prompts.js')).confirm })
627
- : await configureProfileOptions({ ...targetProfile, ...connectionPreferences(app.config, targetProfile || {}, argv) }, argv);
623
+ const preferences = await configureProfileOptions({ ...targetProfile }, argv, {
624
+ interactive: !targetProfile && interactive && !preliminary,
625
+ });
628
626
  let setDefault = argv.makeDefault === true;
629
627
  if (!targetProfile && argv.makeDefault === undefined && interactive && !preliminary) {
630
628
  const { confirm } = await import('../prompts.js');
@@ -131,6 +131,7 @@ export function defaultDocsRoots(opts = {}) {
131
131
 
132
132
  export function openDocsDb(opts = {}) {
133
133
  const dbPath = opts.dbPath || getDocsDbPath();
134
+ ensureDocsCacheDir();
134
135
  fs.mkdirSync(path.dirname(dbPath), { recursive: true });
135
136
  const release = docsReaderLease(dbPath);
136
137
  let db;
@@ -1,84 +1,300 @@
1
- // Documentation search always uses the same API, hosted or self-hosted.
2
- import { searchHostedDocs, getHostedDoc, getHostedDocsStatus } from './client.js';
3
- import { documentationService } from './local.js';
4
- import { startDocumentationServer } from './server.js';
1
+ // jsn docs — ServiceNow documentation search.
2
+
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import net from 'node:net';
6
+ import process from 'node:process';
5
7
  import { declareCapabilities } from '../../capabilities.js';
6
- import { AppError } from '../../errors.js';
8
+ import { formatCommandList } from '../../helpers.js';
7
9
 
8
10
  declareCapabilities('docs', { noInstance: true, skipDailyChecks: true });
9
11
 
10
- async function search(argv, app) {
11
- const query = Array.isArray(argv.query) ? argv.query.join(' ') : argv.query;
12
- const result = await searchHostedDocs({ query, limit: argv.limit, offset: argv.offset, bundle: argv.bundle, serviceUrl: await documentationService(app.config) });
13
- const lines = [];
14
- for (const row of result.results) {
15
- lines.push(`[${row.id}] ${row.title || row.path}`, ` ${row.path}`);
16
- const summary = String(row.summary || row.snippet || '').replace(/\s+/g, ' ').trim();
17
- if (summary) lines.push(` ${summary}`);
18
- lines.push('');
19
- }
20
- const next = result.offset + result.count;
21
- if (result.count && next < result.total && next <= 10000) lines.push(`… ${result.total - next} more results (use --offset ${next} for the next page)`);
22
- if (!result.count) lines.push('No matching documents. Try fewer words or a different term.');
23
- if (result.count) lines.push('Read with "jsn docs --path <exact-path>"; IDs can be pinned with --revision.');
24
- app.ok({ ...result, _formatted: lines.join('\n') + '\n' }, { summary: `${result.count} of ${result.total} result(s) for "${result.query}"` });
25
- }
26
- async function read(argv, app) {
27
- const maxLines = argv.lines ?? 80;
28
- if (!Number.isInteger(maxLines) || maxLines < 1 || maxLines > 10000) throw new AppError('usage_error', 'Use --lines 1–10000.');
29
- const row = await getHostedDoc(argv.path || argv['id-or-path'], { revision: argv.revision, serviceUrl: await documentationService(app.config) });
30
- const title = row.title || row.path;
31
- const lines = row.body.split('\n');
32
- const hint = lines.length > maxLines ? `\n\n… ${lines.length - maxLines} more lines (use --lines ${Math.min(lines.length, 10000)} or --json for full content)` : '';
33
- app.ok({ ...row, _formatted: `${title}\n${'─'.repeat(Math.min(title.length, 80))}\n\n${lines.slice(0, maxLines).join('\n')}${hint}\n` }, { summary: `Doc ${row.id}: ${title}` });
12
+ function formatBytes(n) {
13
+ if (n == null) return '-';
14
+ if (n < 1024) return `${n} B`;
15
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
16
+ return `${(n / (1024 * 1024)).toFixed(1)} MB`;
34
17
  }
35
18
 
36
19
  export function docsCmd(wrap) {
37
20
  return {
38
- command: 'docs [query..]',
39
- defaultPositionals: true,
40
- describe: 'Search ServiceNow documentation (hosted by default; configure your service in setup)',
41
- builder: y => y
42
- .usage('Usage: jsn docs "search terms" [options]')
43
- .positional('query', { type: 'string', describe: 'Search words (up to 200 characters)' })
44
- .option('serve', { type: 'boolean', describe: 'Run the shared documentation server (downloads its index automatically)' })
45
- .option('host', { type: 'string', default: '127.0.0.1', describe: 'Server bind address with --serve' })
46
- .option('port', { type: 'number', default: 3000, describe: 'Server port with --serve' })
47
- .option('limit', { type: 'number', default: 20, describe: 'Results per page (1–50)' })
48
- .option('offset', { type: 'number', default: 0, describe: 'Result offset (0–10000)' })
49
- .option('bundle', { type: 'string', describe: 'Filter by documentation bundle' })
50
- .option('path', { type: 'string', describe: 'Read an exact document path or ID from search results' })
51
- .option('revision', { type: 'string', describe: 'Require the revision returned by search (recommended with IDs)' })
52
- .option('lines', { type: 'number', default: 80, describe: 'Preview lines; JSON contains the full Markdown body' })
53
- // Compatibility spellings remain callable without becoming another menu.
54
- .command({ command: 'install', hidden: true,
55
- builder: y => y.option('source', { type: 'string', choices: ['snapshot', 'github', 'skip'] })
56
- .option('manifest-url', { type: 'string' }),
57
- handler: wrap(async (argv, app) => {
58
- const { installDocumentation } = await import('./install.js');
59
- app.ok(await installDocumentation(argv.source, { manifestURL: argv['manifest-url'] }));
60
- }),
61
- })
62
- .command({ command: 'search <query..>', hidden: true, handler: wrap(search) })
63
- .command({ command: 'show <id-or-path>', hidden: true, handler: wrap(read) })
64
- .command({ command: 'status', hidden: true, handler: wrap(async (_argv, app) => {
65
- const data = await getHostedDocsStatus({ serviceUrl: await documentationService(app.config) });
66
- app.ok(data, { summary: `Documentation service: ${data.state}` });
67
- }) }),
21
+ command: 'docs [subcommand]',
22
+ describe: 'Search ServiceNow documentation locally (install, sync, status, search, serve)',
23
+ builder: (yargs) => {
24
+ return yargs
25
+ .command({ command: 'install', describe: 'Install optional docs: raw GitHub files or a verified prebuilt searchable database',
26
+ builder: y => y.option('source', { type: 'string', choices: ['snapshot', 'github', 'skip'], describe: 'Explicit source; raw GitHub estimated ~5 minutes; snapshot estimate comes from manifest' })
27
+ .option('manifest-url', { type: 'string', describe: 'HTTPS snapshot manifest mirror' }),
28
+ handler: wrap(async (argv, app) => {
29
+ const { installDocumentation, offerDocumentation } = await import('./install.js');
30
+ const { canUsePicker } = await import('../../helpers.js');
31
+ const result = argv.source ? await installDocumentation(argv.source, { manifestURL: argv['manifest-url'] })
32
+ : canUsePicker(app, argv) ? await offerDocumentation(app, argv) : await installDocumentation(undefined);
33
+ app.ok(result, { summary: result.skipped ? 'Documentation skipped' : 'Documentation installed' });
34
+ }),
35
+ })
36
+ .command({ command: 'rollback', describe: 'Restore the previously installed local docs database', handler: wrap(async (_argv, app) => {
37
+ const { rollbackSnapshot } = await import('./snapshot.js');
38
+ app.ok(rollbackSnapshot(), { summary: 'Previous documentation index restored' });
39
+ }) })
40
+ .command({
41
+ command: 'sync',
42
+ describe: 'Clone/update ServiceNowDocs and build the docs.db index',
43
+ builder: (y) => y
44
+ .option('no-embed', { type: 'boolean', describe: 'Skip HRR semantic embeddings' })
45
+ .option('no-ingest', { type: 'boolean', describe: 'Clone/pull only; do not rebuild index' }),
46
+ handler: wrap(async (argv, app) => {
47
+ const { getDocsDbPath, getDocsSourceMarkdownDir } = await import('./db.js');
48
+ const { syncDocs } = await import('./sync.js');
49
+ const result = syncDocs({
50
+ markdownDir: getDocsSourceMarkdownDir(),
51
+ dbPath: getDocsDbPath(),
52
+ embed: argv['no-embed'] !== true,
53
+ noIngest: argv['no-ingest'] === true,
54
+ });
55
+ app.ok(result, { summary: 'Docs sync complete' });
56
+ }),
57
+ })
58
+ .command({
59
+ command: 'status',
60
+ describe: 'Show docs database status',
61
+ handler: wrap(async (argv, app) => {
62
+ const { getDocsDbPath, getDocsSourceDir, getDocsSourceMarkdownDir, docsDbExists, withDocsDb, getDocsIndexStats } = await import('./db.js');
63
+ const dbPath = getDocsDbPath();
64
+ const repoDir = getDocsSourceDir();
65
+ const markdownDir = getDocsSourceMarkdownDir();
66
+ const downloaded = fs.existsSync(path.join(repoDir, '.git')) && fs.existsSync(markdownDir);
67
+ const dbExists = docsDbExists();
68
+
69
+ let state, embedded, documents, bundles, docTypes, syncedAt, dbSize;
70
+ if (dbExists) {
71
+ const stats = withDocsDb({}, (db) => getDocsIndexStats(db));
72
+ ({ documents, bundles, docTypes, syncedAt } = stats);
73
+ const stat = fs.statSync(dbPath);
74
+ dbSize = stat.size;
75
+
76
+ embedded = stats.embeddedCount >= documents && documents > 0;
77
+ if (embedded) state = 'ready';
78
+ else if (documents > 0) state = 'indexed (not embedded)';
79
+ else state = 'empty';
80
+ } else {
81
+ state = downloaded ? 'not indexed' : 'not downloaded';
82
+ embedded = false;
83
+ }
84
+
85
+ // Quick probe to see if the server is running on the default port.
86
+ const served = await new Promise((resolve) => {
87
+ const sock = new net.Socket();
88
+ sock.setTimeout(500);
89
+ sock.on('connect', () => { sock.destroy(); resolve(true); });
90
+ sock.on('error', () => resolve(false));
91
+ sock.on('timeout', () => { sock.destroy(); resolve(false); });
92
+ sock.connect(3000, '127.0.0.1');
93
+ });
94
+
95
+ const { docsSnapshotStatus } = await import('./snapshot.js');
96
+ const snapshot = docsSnapshotStatus();
97
+ let available = null;
98
+ try { available = JSON.parse(fs.readFileSync(`${dbPath}.available.json`, 'utf8')); } catch { /* No background update information. */ }
99
+ app.ok({
100
+ state,
101
+ ...(snapshot ? { snapshot: { revision: snapshot.revision, schema: snapshot.schema } } : {}),
102
+ ...(snapshot && available?.installed === snapshot.revision && available.revision !== snapshot.revision ? { updateAvailable: { revision: available.revision, command: 'jsn docs install --source snapshot' } } : {}),
103
+ downloaded: { ok: downloaded, path: repoDir },
104
+ db: { ok: dbExists, path: dbPath },
105
+ embedded: { ok: embedded },
106
+ ...(documents != null && { documents, bundles, docTypes, syncedAt: syncedAt ? new Date(parseInt(syncedAt, 10)).toISOString() : null }),
107
+ ...(dbSize != null && { dbSizeHuman: formatBytes(dbSize) }),
108
+ ...(served && { served: 'http://127.0.0.1:3000' }),
109
+ }, { summary: `Docs database: ${state}` });
110
+ }),
111
+ })
112
+ .command({
113
+ command: 'search <query>',
114
+ describe: 'Search docs (FTS5 + optional HRR hybrid rerank)',
115
+ builder: (y) => y
116
+ .positional('query', { type: 'string', describe: 'Search query' })
117
+ .option('limit', { type: 'number', default: 20, describe: 'Max results' })
118
+ .option('offset', { type: 'number', default: 0, describe: 'Result offset' })
119
+ .option('bundle', { type: 'string', describe: 'Filter by bundle' })
120
+ .option('doc-type', { type: 'string', describe: 'Filter by doc type' })
121
+ .option('mode', { type: 'string', choices: ['keyword', 'hybrid'], default: 'hybrid', describe: 'Search mode' }),
122
+ handler: wrap(async (argv, app) => {
123
+ const { ensureDocumentation } = await import('./install.js');
124
+ await ensureDocumentation(app, argv);
125
+ const { searchDocs } = await import('./search.js');
126
+ const result = searchDocs({
127
+ query: argv.query,
128
+ limit: argv.limit,
129
+ offset: argv.offset,
130
+ bundle: argv.bundle,
131
+ docType: argv['doc-type'],
132
+ mode: argv.mode,
133
+ });
134
+
135
+ // Build a readable text blob for styled TTY output.
136
+ const lines = [];
137
+ for (const r of result.results) {
138
+ const title = r.title || r.path || '(untitled)';
139
+ const snippet = (r.snippet || r.body || '')
140
+ .replace(/\\n/g, ' ')
141
+ .replace(/\s+/g, ' ')
142
+ .trim()
143
+ .substring(0, 200);
144
+ lines.push(`[${r.id}] ${title}`);
145
+ if (snippet) lines.push(` ${snippet}`);
146
+ lines.push('');
147
+ }
148
+
149
+ const hasMore = result.total > result.count;
150
+ if (hasMore) {
151
+ const nextOffset = (result.count + (argv.offset || 0));
152
+ lines.push(`… ${result.total - result.count} more results (use --offset ${nextOffset} for next page)`);
153
+ }
154
+
155
+ app.ok({
156
+ _formatted: lines.join('\n'),
157
+ query: result.query,
158
+ mode: result.mode,
159
+ total: result.total,
160
+ count: result.count,
161
+ results: result.results,
162
+ }, { summary: `${result.count} of ${result.total} result(s) for "${result.query}" (${result.mode})` });
163
+ }),
164
+ })
165
+ .command({
166
+ command: 'show <id-or-path>',
167
+ describe: 'Show a documentation page by id or path',
168
+ builder: (y) => y
169
+ .positional('id-or-path', { type: 'string', describe: 'Document id (number) or file path' })
170
+ .option('lines', { type: 'number', default: 80, describe: 'Lines of body to show in terminal (use --json for full content)' }),
171
+ handler: wrap(async (argv, app) => {
172
+ const { getDocByIdOrPath } = await import('./search.js');
173
+ const idOrPath = argv['id-or-path'];
174
+ const row = getDocByIdOrPath(idOrPath);
175
+
176
+ if (!row) {
177
+ throw Object.assign(new Error(`No doc found for "${idOrPath}"`), { code: 'not_found' });
178
+ }
179
+
180
+ let fm = {};
181
+ try { fm = JSON.parse(row.frontmatter || '{}'); } catch { /* ignore */ }
182
+
183
+ const title = row.title || fm.title || row.path || '(untitled)';
184
+ const header = `${title}\n${'─'.repeat(Math.min(title.length, 80))}`;
185
+ const body = row.body || '';
186
+ const bodyLines = body.split('\n');
187
+ const truncated = bodyLines.length > argv.lines;
188
+ const preview = bodyLines.slice(0, argv.lines).join('\n');
189
+ const hint = truncated ? `\n\n… ${bodyLines.length - argv.lines} more lines (use --lines ${bodyLines.length} or --json for full content)` : '';
190
+
191
+ app.ok({
192
+ id: row.id,
193
+ path: row.path,
194
+ title: row.title,
195
+ bundle: row.bundle,
196
+ release: row.release,
197
+ canonical_url: fm.canonical_url || null,
198
+ body,
199
+ _formatted: `${header}\n\n${preview}${hint}`,
200
+ }, { summary: `Doc ${row.id}: ${title}` });
201
+ }),
202
+ })
203
+ .command({
204
+ command: 'serve',
205
+ describe: 'Start the docs search web UI',
206
+ builder: (y) => y
207
+ .option('port', { type: 'number', default: 3000, describe: 'HTTP port' })
208
+ .option('host', { type: 'string', default: '127.0.0.1', describe: 'Bind address' })
209
+ .option('expose', { type: 'boolean', default: false, describe: 'Bind to 0.0.0.0 to expose on the network' }),
210
+ handler: wrap(async (argv, _app) => {
211
+ const { serveDocs } = await import('./serve.js');
212
+ try {
213
+ const host = argv.expose ? '0.0.0.0' : argv.host;
214
+ await serveDocs({ port: argv.port, host });
215
+ } catch (err) {
216
+ process.stderr.write(`Error: ${err.message}\n`);
217
+ process.exit(1);
218
+ }
219
+ }),
220
+ })
221
+ .command({
222
+ command: 'embed',
223
+ describe: 'Backfill or refresh HRR semantic embeddings',
224
+ handler: wrap(async (argv, app) => {
225
+ const { embedDocs } = await import('./embed.js');
226
+ const result = embedDocs();
227
+ app.ok(result, { summary: `Embedded ${result.embedded} of ${result.total} docs` });
228
+ }),
229
+ })
230
+ .command({
231
+ command: 'refresh',
232
+ describe: 'Incrementally refresh docs.db from existing source clone',
233
+ handler: wrap(async (argv, app) => {
234
+ const { getDocsSourceMarkdownDir } = await import('./db.js');
235
+ const { refreshDocs } = await import('./refresh.js');
236
+ const result = refreshDocs({ docsDir: getDocsSourceMarkdownDir() });
237
+ app.ok(result, { summary: `Refresh complete: +${result.added} ~${result.updated} -${result.removed} =${result.unchanged}` });
238
+ }),
239
+ })
240
+ .command({
241
+ command: 'community <action>',
242
+ describe: 'Sync ServiceNow Community articles into the searchable docs index',
243
+ builder: (y) => y
244
+ .command({
245
+ command: 'sync',
246
+ describe: 'Fetch community hub pages (+ linked articles with --expand) and index them',
247
+ builder: (yy) => yy
248
+ .option('expand', { type: 'boolean', describe: 'Also fetch every linked community article found on the hub pages' })
249
+ .option('force', { type: 'boolean', describe: 'Re-fetch articles already downloaded' })
250
+ .option('sources', { type: 'string', describe: 'Path to a community-sources.json (default: bundled)' })
251
+ .option('delay-ms', { type: 'number', describe: 'Delay between article fetches (default: 500)' }),
252
+ handler: wrap(async (argv, app) => {
253
+ const { syncCommunity } = await import('./community.js');
254
+ const result = await syncCommunity({
255
+ sourcesFile: argv.sources,
256
+ expand: argv.expand === true,
257
+ force: argv.force === true,
258
+ delayMs: argv['delay-ms'],
259
+ });
260
+ app.ok(result, {
261
+ summary: `Community sync: ${result.hubs.length} hub(s), ${result.articles.length} article(s), ${result.skipped.length} skipped, ${result.errors.length} error(s)`,
262
+ });
263
+ }),
264
+ })
265
+ .command({
266
+ command: 'list',
267
+ describe: 'List community docs currently in the index',
268
+ handler: wrap(async (argv, app) => {
269
+ const { listCommunityDocs } = await import('./community.js');
270
+ const result = listCommunityDocs();
271
+ const lines = result.docs.map((d) => `[${d.id}] ${d.title || d.path} (${d.doc_type})`);
272
+ app.ok({
273
+ _formatted: lines.length ? lines.join('\n') : '(no community docs indexed yet)',
274
+ total: result.total,
275
+ docs: result.docs,
276
+ }, { summary: `${result.total} community doc(s) indexed` });
277
+ }),
278
+ })
279
+ .demandCommand(1, 'Specify an action: sync or list'),
280
+ });
281
+ },
68
282
  handler: wrap(async (argv, app) => {
69
- if (argv.serve) {
70
- if (!Number.isInteger(argv.port) || argv.port < 0 || argv.port > 65535) throw new AppError('usage_error', 'Use a port between 0 and 65535.');
71
- const { server, url } = await startDocumentationServer({ host: argv.host, port: argv.port });
72
- app.ok({ url, state: 'listening' }, { summary: 'Documentation server started; the index updates automatically.' });
73
- for (const signal of ['SIGINT', 'SIGTERM']) process.once(signal, () => server.close());
74
- return;
75
- }
76
- if (argv.path) return read(argv, app);
77
- if (argv.query?.length) return search(argv, app);
78
- const service = await documentationService(app.config);
79
- const summary = 'Search ServiceNow documentation';
80
- app.ok({ command: 'docs', service,
81
- _formatted: `jsn docs "search terms"\njsn docs --path <exact-path>\n\nService: ${service}\nChange documentation preferences in jsn setup → Advanced settings.\nNo ServiceNow connection is needed. Hosted mode downloads no database.\n`,
283
+ const { getDocsDbPath } = await import('./db.js');
284
+ const subcommands = argv.subcommands || [];
285
+ const summary = 'jsn docs — optional local documentation (install, sync, status, search, show, serve, rollback).';
286
+ app.ok({
287
+ command: 'docs',
288
+ subcommands,
289
+ _formatted: formatCommandList({
290
+ title: summary,
291
+ commands: subcommands,
292
+ footer: [
293
+ 'Tip: use "jsn docs serve --expose" to bind to 0.0.0.0 and share on your network.',
294
+ `Docs DB: ${getDocsDbPath()} (run "jsn docs status" for details, or query directly with sqlite3)`,
295
+ 'Run "jsn docs <command> --help" for details.',
296
+ ].join('\n'),
297
+ }),
82
298
  }, { summary });
83
299
  }),
84
300
  };
@@ -1,5 +1,3 @@
1
- import { configureGlobalDefaults, configureDocumentation } from '../setup-preferences.js';
2
- import { select } from '../prompts.js';
3
1
  import { loginWizard, loginProfile, showAuthStatus, switchProfile, modifyProfile, logoutProfile, removeConnection } from './auth.js';
4
2
  import { errUsageHint } from '../errors.js';
5
3
  import { declareCapabilities } from '../capabilities.js';
@@ -16,7 +14,7 @@ const HUB_CHOICES = [
16
14
  { name: 'Change settings', value: 'modify', command: 'jsn auth modify --profile <name> --read-only --confirm-deletes --no-include-counts' },
17
15
  { name: 'Sign out (keep the profile)', value: 'logout', command: 'jsn auth logout --profile <name> --force (only after explicit approval)' },
18
16
  { name: 'Remove a connection', value: 'remove', command: 'jsn auth remove <name>' },
19
- { name: 'Advanced settings', value: 'advanced', command: 'jsn setup' },
17
+ { name: 'Install optional offline documentation', value: 'docs', command: 'jsn docs install --source snapshot|github|skip' },
20
18
  ];
21
19
 
22
20
  const setupHelp = () => [
@@ -71,9 +69,8 @@ export const authHubPrompt = async (...args) => {
71
69
  };
72
70
 
73
71
  /** Interactive hub: what do you want to do? Returns an action or undefined on exit. */
74
- export async function authHubMenu({ promptFn = authHubPrompt, input, output, hasProfiles = true } = {}) {
75
- const choices = hasProfiles ? HUB_CHOICES : HUB_CHOICES.filter(choice => ['add', 'advanced'].includes(choice.value));
76
- return promptFn({ message: 'What would you like to do?', choices }, { input, output });
72
+ export async function authHubMenu({ promptFn = authHubPrompt, input, output } = {}) {
73
+ return promptFn({ message: 'What would you like to do?', choices: HUB_CHOICES }, { input, output });
77
74
  }
78
75
 
79
76
  /**
@@ -93,15 +90,6 @@ export async function dispatchSetupAction(app, argv, action) {
93
90
  return logoutProfile(argv, app);
94
91
  } else if (action === 'remove') {
95
92
  return removeConnection(argv, app);
96
- } else if (action === 'advanced') {
97
- const setting = await select({ message: 'Advanced settings', choices: [
98
- { name: 'Defaults for future connections', value: 'defaults' },
99
- { name: 'Documentation source', value: 'docs' },
100
- { name: 'Back', value: 'back' },
101
- ] });
102
- if (setting === 'defaults') await configureGlobalDefaults(app.config, { documentation: false });
103
- if (setting === 'docs') await configureDocumentation(app.config);
104
- if (setting !== 'back') app.ok({ settings: setting }, { summary: 'Settings saved; existing connections unchanged' });
105
93
  } else if (action === 'modify') {
106
94
  return modifyProfile(app, argv);
107
95
  }
@@ -113,7 +101,7 @@ export async function dispatchSetupAction(app, argv, action) {
113
101
  export function setupCmd(wrap) {
114
102
  return {
115
103
  command: 'setup',
116
- describe: 'Set up JSN defaults and manage ServiceNow connections (interactive)',
104
+ describe: 'Set up and manage your ServiceNow instances (interactive)',
117
105
  builder: y => y.option('docs-source', { type: 'string', choices: ['snapshot', 'github', 'skip'], describe: 'Install optional documentation directly without the authentication wizard' }).epilogue(setupHelp()),
118
106
  handler: wrap(async (argv, app) => {
119
107
  if (argv['docs-source']) {
@@ -126,18 +114,25 @@ export function setupCmd(wrap) {
126
114
  throw errUsageHint('"jsn setup" is interactive. Use explicit auth commands instead.', setupHelp());
127
115
  }
128
116
  const profileNames = Object.keys(app.config.profiles || {});
129
- const firstSetup = !app.config.connectionDefaults;
130
- if (firstSetup) await configureGlobalDefaults(app.config);
131
- else if (!app.config.docs) await configureDocumentation(app.config);
132
- if (profileNames.length === 0 && firstSetup) {
117
+ if (profileNames.length === 0) {
133
118
  const result = await loginWizard(app, argv);
134
119
  await showAuthStatus({ ...argv, profile: result.profileName }, app);
120
+ const { docsDbExists } = await import('./docs/db.js');
121
+ if (!docsDbExists()) {
122
+ const { offerDocumentation } = await import('./docs/install.js');
123
+ app.ok(await offerDocumentation(app, argv));
124
+ }
135
125
  return;
136
126
  }
137
- const action = await authHubMenu({ hasProfiles: profileNames.length > 0 });
127
+ const action = await authHubMenu();
138
128
  if (action === undefined) return;
129
+ if (action === 'docs') {
130
+ const { offerDocumentation } = await import('./docs/install.js');
131
+ app.ok(await offerDocumentation(app, argv));
132
+ return;
133
+ }
139
134
  const result = await dispatchSetupAction(app, argv, action);
140
- if (!['status', 'advanced'].includes(action)) await showAuthStatus({ ...argv, profile: result?.profile || result?.profileName }, app);
135
+ if (action !== 'status') await showAuthStatus({ ...argv, profile: result?.profile || result?.profileName }, app);
141
136
  }),
142
137
  };
143
138
  }
package/src/config.js CHANGED
@@ -46,11 +46,6 @@ function loadFromFile(cfg, filePath, source) {
46
46
  try {
47
47
  const data = fs.readFileSync(filePath, 'utf-8');
48
48
  const fileCfg = JSON.parse(data);
49
- // Installation-wide preferences are never taken from a project config.
50
- if (source === 'global') {
51
- if (fileCfg.connection_defaults && typeof fileCfg.connection_defaults === 'object') cfg.connectionDefaults = fileCfg.connection_defaults;
52
- if (fileCfg.docs && typeof fileCfg.docs === 'object') cfg.docs = fileCfg.docs;
53
- }
54
49
  if (fileCfg.instance_url) {
55
50
  cfg.instanceURL = fileCfg.instance_url;
56
51
  cfg.sources.instance_url = source;
@@ -92,8 +87,6 @@ export function createConfig() {
92
87
  activeProfile: '',
93
88
  format: 'auto',
94
89
  sources: {},
95
- connectionDefaults: null,
96
- docs: null,
97
90
  };
98
91
  }
99
92
 
@@ -127,8 +120,6 @@ export function saveConfig(cfg) {
127
120
  const dir = globalConfigDir();
128
121
  fs.mkdirSync(dir, { recursive: true, mode: 0o750 });
129
122
  const payload = {
130
- connection_defaults: cfg.connectionDefaults || undefined,
131
- docs: cfg.docs || undefined,
132
123
  instance_url: cfg.instanceURL || undefined,
133
124
  profiles: Object.keys(cfg.profiles).length > 0 ? cfg.profiles : undefined,
134
125
  default_profile: cfg.defaultProfile || undefined,
@@ -1,77 +0,0 @@
1
- // Public documentation service. Deliberately independent of instance credentials.
2
- import { AppError } from '../../errors.js';
3
-
4
- export const DEFAULT_DOCS_URL = 'https://jsn.jace.pro';
5
- const MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
6
- export function docsServiceUrl(value = process.env.JSN_DOCS_URL || DEFAULT_DOCS_URL) {
7
- let url;
8
- try { url = new URL(value); } catch { throw new AppError('usage_error', 'Invalid documentation service URL.'); }
9
- if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) {
10
- throw new AppError('usage_error', 'Documentation service URL must be HTTP(S), without credentials, a query, or a fragment.');
11
- }
12
- url.pathname = url.pathname.replace(/\/+$/, '') + '/';
13
- return url.toString();
14
- }
15
- export function configuredDocsService(config = {}) {
16
- return docsServiceUrl(process.env.JSN_DOCS_URL || config.docs?.url || DEFAULT_DOCS_URL);
17
- }
18
- async function request(endpoint, params, options = {}) {
19
- const service = docsServiceUrl(options.serviceUrl);
20
- const url = new URL(endpoint, service);
21
- for (const [key, value] of Object.entries(params)) if (value !== undefined && value !== null && value !== '') url.searchParams.set(key, String(value));
22
- let response, data;
23
- try {
24
- response = await fetch(url, { headers: { Accept: 'application/json' }, signal: AbortSignal.timeout(20_000) });
25
- let bytes = 0;
26
- const chunks = [];
27
- for await (const chunk of response.body) {
28
- bytes += chunk.length;
29
- if (bytes > MAX_RESPONSE_BYTES) throw new AppError('api_error', 'Documentation service response is too large.');
30
- chunks.push(chunk);
31
- }
32
- try { data = JSON.parse(Buffer.concat(chunks).toString('utf8')); }
33
- catch { throw new AppError('api_error', 'Documentation service did not return JSON.', 'Check JSN_DOCS_URL points to a JSN documentation service.'); }
34
- } catch (error) {
35
- if (error instanceof AppError) throw error;
36
- throw new AppError('network_error', 'Could not reach the documentation service.', `Check your connection and JSN_DOCS_URL (${service}).`, 0, error);
37
- }
38
- if (!response.ok) {
39
- const code = response.status === 404 ? 'not_found' : response.status === 429 ? 'rate_limited' : response.status === 400 ? 'usage_error' : 'api_error';
40
- const message = typeof data?.error === 'string' ? data.error.slice(0, 300) : `Documentation service returned HTTP ${response.status}.`;
41
- const hint = response.status === 409 ? 'Search again for the current revision, or retrieve the document by its exact path.'
42
- : response.status === 429 ? 'Wait before retrying.' : response.status >= 500 ? 'Try again later; the documentation service may be updating or unavailable.' : '';
43
- throw new AppError(code, message, hint, response.status);
44
- }
45
- return { data, service };
46
- }
47
- function invalidResponse() {
48
- return new AppError('api_error', 'Unexpected documentation service response.', 'Check JSN_DOCS_URL and the documentation service version.');
49
- }
50
- export async function searchHostedDocs(options = {}) {
51
- const query = String(options.query || '').trim();
52
- const limit = options.limit ?? 20, offset = options.offset ?? 0;
53
- if (!query || query.length > 200) throw new AppError('usage_error', 'Search query must contain 1–200 characters.');
54
- if (!Number.isInteger(limit) || limit < 1 || limit > 50 || !Number.isInteger(offset) || offset < 0 || offset > 10000) {
55
- throw new AppError('usage_error', 'Use --limit 1–50 and --offset 0–10000.');
56
- }
57
- const { data, service } = await request('api/docs/search', { q: query, limit, offset, bundle: options.bundle }, options);
58
- if (!data || !Array.isArray(data.results) || data.results.length > limit || data.count !== data.results.length ||
59
- !Number.isInteger(data.total) || data.total < data.count || typeof data.revision !== 'string' ||
60
- !data.results.every(row => row && Number.isInteger(row.id) && typeof row.path === 'string')) throw invalidResponse();
61
- return { ...data, query, limit, offset, service };
62
- }
63
- export async function getHostedDoc(idOrPath, options = {}) {
64
- const identifier = String(idOrPath || '');
65
- if (!identifier) throw new AppError('usage_error', 'Provide a document ID or exact path.');
66
- const numeric = /^\d+$/.test(identifier);
67
- const { data, service } = await request(numeric ? `api/docs/${identifier}` : 'api/docs/document', {
68
- ...(numeric ? {} : { path: identifier }), revision: options.revision,
69
- }, options);
70
- if (!data || !data.document || typeof data.document.body !== 'string' || typeof data.document.path !== 'string' || typeof data.revision !== 'string') throw invalidResponse();
71
- return { ...data.document, revision: data.revision, service };
72
- }
73
- export async function getHostedDocsStatus(options = {}) {
74
- const { data, service } = await request('api/docs/status', {}, options);
75
- if (!data || typeof data.state !== 'string') throw invalidResponse();
76
- return { ...data, service };
77
- }
@@ -1,15 +0,0 @@
1
- // The Rails adapter uses this JSON-lines bridge to the same Node search engine.
2
- import readline from 'node:readline';
3
- import { DocumentationIndex, documentationSummary } from './index.js';
4
- let index;
5
- try {
6
- for await (const line of readline.createInterface({ input: process.stdin, crlfDelay: Infinity })) {
7
- try {
8
- const { operation, arguments: args = {} } = JSON.parse(line);
9
- if (operation !== 'summary') index ||= new DocumentationIndex(process.env.DOCS_STORAGE_DIR);
10
- const value = operation === 'summary' ? documentationSummary(args) : operation === 'revision' ? index.revision()
11
- : operation === 'search' ? index.search(args) : operation === 'document' ? index.document(args) : null;
12
- process.stdout.write(JSON.stringify({ value }) + '\n');
13
- } catch (error) { process.stdout.write(JSON.stringify({ error: error.status ? error.message : 'Documentation search is temporarily unavailable.', status: error.status || 503 }) + '\n'); }
14
- }
15
- } finally { index?.close(); }
@@ -1,81 +0,0 @@
1
- // One search engine for the hosted website and the optional local service.
2
- import fs from 'node:fs';
3
- import path from 'node:path';
4
- import Database from 'better-sqlite3';
5
-
6
- export class DocumentationError extends Error {
7
- constructor(message, status = 503) { super(message); this.status = status; }
8
- }
9
- export function documentationStatus(storage) {
10
- try {
11
- const value = JSON.parse(fs.readFileSync(path.join(storage, 'status.json'), 'utf8'));
12
- return Object.fromEntries(['state', 'checkedAt', 'publishedAt', 'documents', 'revision'].filter(key => key in value).map(key => [key, value[key]]));
13
- } catch { return { state: 'unavailable' }; }
14
- }
15
- function plain(value) {
16
- return String(value).replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1').replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
17
- .replace(/\\([\p{P}\p{S}])/gu, '$1').replace(/[`*#]/g, '').replace(/<[^>]*>/g, '')
18
- .replace(/&(?:amp|lt|gt|quot|#39);/g, entity => ({ '&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '"', '&#39;': "'" })[entity])
19
- .replace(/\s+/g, ' ').trim();
20
- }
21
- function firstParagraph(body) {
22
- let fenced = false, current = [];
23
- const paragraphs = [];
24
- for (const line of String(body).split('\n')) {
25
- if (/^ {0,3}(?:`{3,}|~{3,})/.test(line)) { fenced = !fenced; continue; }
26
- if (fenced || /^(?: {4}|\t)/.test(line)) continue;
27
- if (!line.trim()) { if (current.length) paragraphs.push(current.join(' ')); current = []; }
28
- else if (!/^\s*(?:\||#{1,6}\s|<|[-*+]\s|\d+\.\s|\*?\*?Parent Topic:)/i.test(line)) current.push(line.trim());
29
- }
30
- if (current.length) paragraphs.push(current.join(' '));
31
- return plain(paragraphs.find(text => text.length > 30) || '');
32
- }
33
- export function documentationSummary(input) {
34
- const { frontmatter, preview, ...row } = input;
35
- let metadata;
36
- try { metadata = JSON.parse(frontmatter || '{}'); } catch { metadata = {}; }
37
- if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) metadata = {};
38
- const description = typeof metadata.description === 'string' ? plain(metadata.description) : '';
39
- const excerpt = firstParagraph(preview || '');
40
- let summary = description || excerpt || `Read ${row.title || 'this reference'} in the ServiceNow documentation.`;
41
- if (summary.length > 280) summary = summary.slice(0, 280).match(/^(.{60,}[.!?])(?:\s|$)/)?.[1] || summary.slice(0, 279).replace(/\s+\S*$/, '') + '…';
42
- const classification = typeof metadata.classification === 'string' && metadata.classification ? metadata.classification : String(row.path || '').split('/')[0];
43
- const category = plain(classification.replaceAll('-', ' '));
44
- return { ...row, doc_type: row.doc_type || metadata.topic_type || null, summary,
45
- summary_source: description ? 'description' : excerpt ? 'paragraph' : 'fallback',
46
- category: typeof metadata.product === 'string' && metadata.product.trim() ? plain(metadata.product) : category.charAt(0).toUpperCase() + category.slice(1).replace(/^pi /, 'PI '),
47
- };
48
- }
49
- export class DocumentationIndex {
50
- constructor(storage) {
51
- try { this.db = new Database(path.join(storage, 'docs.sqlite3'), { readonly: true, fileMustExist: true, timeout: 2000 }); }
52
- catch { throw new DocumentationError('Documentation is being prepared. Please try again shortly.'); }
53
- }
54
- close() { this.db.close(); }
55
- revision() { return this.db.prepare("SELECT value FROM meta WHERE key = 'source_revision'").get()?.value || ''; }
56
- search({ query, limit = 20, offset = 0, bundle } = {}) {
57
- const text = String(query || '').trim();
58
- if (!text || text.length > 200) throw new DocumentationError('Enter a search of 1 to 200 characters.', 400);
59
- const tokens = text.match(/[\p{L}\p{N}_]+/gu)?.slice(0, 20);
60
- if (!tokens?.length) throw new DocumentationError('Enter a word to search for.', 400);
61
- limit = Number(limit); offset = Number(offset);
62
- if (!Number.isInteger(limit) || limit < 1 || limit > 50 || !Number.isInteger(offset) || offset < 0 || offset > 10000) throw new DocumentationError('Limit must be 1–50 and offset 0–10000.', 400);
63
- const filter = bundle ? ' AND d.bundle = ?' : '';
64
- const binds = [tokens.map(token => `"${token}"`).join(' AND '), ...(bundle ? [bundle] : [])];
65
- const total = this.db.prepare(`SELECT COUNT(*) AS n FROM docs_fts JOIN docs d ON d.id=docs_fts.rowid WHERE docs_fts MATCH ?${filter}`).get(...binds).n;
66
- const results = this.db.prepare(`SELECT d.id, d.path, d.title, d.bundle, d.doc_type, d.release, d.frontmatter,
67
- substr(d.body, 1, 12000) AS preview, snippet(docs_fts, 1, '', '', ' … ', 24) AS snippet
68
- FROM docs_fts JOIN docs d ON d.id=docs_fts.rowid WHERE docs_fts MATCH ?${filter}
69
- ORDER BY CASE WHEN lower(d.title) = lower(?) THEN 0 WHEN instr(lower(d.title), lower(?)) = 1 THEN 1
70
- WHEN instr(lower(d.title), lower(?)) > 0 THEN 2 ELSE 3 END, bm25(docs_fts, 10.0, 1.0), d.id LIMIT ? OFFSET ?`)
71
- .all(...binds, text, text, text, limit, offset).map(documentationSummary);
72
- return { query: text, revision: this.revision(), total, count: results.length, limit, offset, results };
73
- }
74
- document({ id, path: docPath } = {}) {
75
- const select = 'SELECT id, path, title, bundle, doc_type, release, body FROM docs WHERE';
76
- const row = docPath ? this.db.prepare(`${select} path = ?`).get(docPath)
77
- : /^\d{1,18}$/.test(String(id)) ? this.db.prepare(`${select} id = ?`).get(String(id)) : null;
78
- if (!row) throw new DocumentationError('Document not found.', 404);
79
- return row;
80
- }
81
- }
@@ -1,68 +0,0 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import { fork } from 'node:child_process';
4
- import { fileURLToPath } from 'node:url';
5
- import { setTimeout as delay } from 'node:timers/promises';
6
- import { AppError } from '../../errors.js';
7
- import { configuredDocsService, docsServiceUrl } from './client.js';
8
- import os from 'node:os';
9
-
10
- function storageDirectory() { return path.join(process.env.JSN_DATA_HOME || path.join(os.homedir(), '.jsn'), 'docs-service'); }
11
- async function healthy(state) {
12
- try {
13
- const url = new URL(state.url);
14
- if (url.hostname !== '127.0.0.1' || url.protocol !== 'http:') return false;
15
- process.kill(state.pid, 0);
16
- const response = await fetch(new URL('up', url), { signal: AbortSignal.timeout(1000) });
17
- return response.ok && (await response.json()).service === 'jsn-docs';
18
- } catch { return false; }
19
- }
20
- export async function ensureLocalDocumentation({ storage = storageDirectory() } = {}) {
21
- fs.mkdirSync(storage, { recursive: true, mode: 0o700 });
22
- const stateFile = path.join(storage, 'server.json'), lock = path.join(storage, 'server-start.lock');
23
- const state = () => { try { return JSON.parse(fs.readFileSync(stateFile, 'utf8')); } catch { return {}; } };
24
- if (await healthy(state())) return state();
25
- let acquired = false;
26
- for (let attempt = 0; attempt < 100 && !acquired; attempt++) {
27
- try { fs.mkdirSync(lock); fs.writeFileSync(path.join(lock, 'pid'), String(process.pid)); acquired = true; }
28
- catch (error) {
29
- if (error.code !== 'EEXIST') throw error;
30
- if (await healthy(state())) return state();
31
- try {
32
- const pid = Number(fs.readFileSync(path.join(lock, 'pid'), 'utf8'));
33
- if (pid) process.kill(pid, 0);
34
- else if (Date.now() - fs.statSync(lock).mtimeMs > 30_000) fs.rmSync(lock, { recursive: true, force: true });
35
- } catch (probe) { if (probe.code === 'ESRCH') fs.rmSync(lock, { recursive: true, force: true }); }
36
- await delay(100);
37
- }
38
- }
39
- if (!acquired) throw new AppError('network_error', 'The local documentation service is still starting. Try again shortly.');
40
- let child;
41
- try {
42
- if (await healthy(state())) return state();
43
- const log = fs.openSync(path.join(storage, 'server.log'), 'a', 0o600);
44
- try {
45
- child = fork(fileURLToPath(new URL('./server.js', import.meta.url)), [], { detached: true, execArgv: [],
46
- env: { ...process.env, DOCS_STORAGE_DIR: storage, JSN_DOCS_HOST: '127.0.0.1', JSN_DOCS_PORT: '0' }, stdio: ['ignore', log, log, 'ipc'] });
47
- } finally { fs.closeSync(log); }
48
- const next = await new Promise((resolve, reject) => {
49
- const timer = setTimeout(() => { child.kill(); reject(new Error('Timed out starting the documentation server.')); }, 10_000);
50
- child.once('message', message => { clearTimeout(timer); resolve(message); });
51
- child.once('error', error => { clearTimeout(timer); reject(error); });
52
- child.once('exit', () => { clearTimeout(timer); reject(new Error('The documentation server stopped before it was ready.')); });
53
- });
54
- if (!await healthy(next)) throw new Error('Local documentation server did not become healthy.');
55
- fs.writeFileSync(stateFile + '.tmp', JSON.stringify(next) + '\n', { mode: 0o600 });
56
- fs.renameSync(stateFile + '.tmp', stateFile);
57
- child.unref();
58
- return next;
59
- } catch (error) {
60
- child?.kill();
61
- throw new AppError('network_error', 'Could not start the local documentation service.', error.message);
62
- } finally { fs.rmSync(lock, { recursive: true, force: true }); }
63
- }
64
- export async function documentationService(config = {}) {
65
- if (process.env.JSN_DOCS_URL) return docsServiceUrl(process.env.JSN_DOCS_URL);
66
- if (config.docs?.source === 'local') return (await ensureLocalDocumentation()).url;
67
- return configuredDocsService(config);
68
- }
@@ -1,60 +0,0 @@
1
- import http from 'node:http';
2
- import fs from 'node:fs';
3
- import path from 'node:path';
4
- import os from 'node:os';
5
- import { fork } from 'node:child_process';
6
- import { fileURLToPath } from 'node:url';
7
- import { DocumentationIndex, documentationStatus } from './index.js';
8
-
9
- export function serviceStorage() { return process.env.DOCS_STORAGE_DIR || path.join(process.env.JSN_DATA_HOME || path.join(os.homedir(), '.jsn'), 'docs-service'); }
10
- export async function startDocumentationServer({ storage = serviceStorage(), host = '127.0.0.1', port = 0, refresh = true } = {}) {
11
- fs.mkdirSync(storage, { recursive: true });
12
- let worker;
13
- const server = http.createServer((req, res) => {
14
- const send = (status, value) => { res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' }); res.end(JSON.stringify(value)); };
15
- if (req.method !== 'GET') return send(405, { error: 'Use GET.' });
16
- let index;
17
- try {
18
- const url = new URL(req.url, 'http://localhost');
19
- if (url.pathname === '/up') return send(200, { service: 'jsn-docs' });
20
- if (url.pathname === '/api/docs/status') return send(200, documentationStatus(storage));
21
- if (!['/api/docs/search', '/api/docs/document'].includes(url.pathname) && !/^\/api\/docs\/\d{1,18}$/.test(url.pathname)) return send(404, { error: 'Not found.' });
22
- index = new DocumentationIndex(storage);
23
- const params = Object.fromEntries(url.searchParams);
24
- 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 }));
25
- const revision = index.revision();
26
- if (params.revision && params.revision !== revision) return send(409, { error: 'Documentation has changed. Search again or retrieve by exact path.' });
27
- return send(200, { revision, document: index.document({ path: params.path, id: url.pathname.split('/').at(-1) }) });
28
- } catch (error) { send(error.status || 503, { error: error.status ? error.message : 'Documentation search is temporarily unavailable.' }); }
29
- finally { index?.close(); }
30
- });
31
- function checkForUpdates() {
32
- if (worker) return;
33
- const status = documentationStatus(storage);
34
- const elapsed = Date.now() - Date.parse(status.checkedAt || 0);
35
- if (elapsed < (status.state === 'ready' ? 24 : 1) * 3600_000) return;
36
- const log = fs.openSync(path.join(storage, 'sync.log'), 'a', 0o600);
37
- try {
38
- worker = fork(fileURLToPath(new URL('./sync-service.js', import.meta.url)), [], {
39
- env: { ...process.env, DOCS_STORAGE_DIR: storage }, stdio: ['ignore', log, log, 'ipc'], execArgv: [],
40
- });
41
- worker.on('exit', () => { worker = null; });
42
- worker.on('error', () => { worker = null; });
43
- } finally { fs.closeSync(log); }
44
- }
45
- await new Promise((resolve, reject) => { server.once('error', reject); server.listen(port, host, resolve); });
46
- const interval = refresh ? setInterval(checkForUpdates, 60_000) : null;
47
- interval?.unref();
48
- if (refresh) checkForUpdates();
49
- server.on('close', () => { clearInterval(interval); worker?.kill('SIGTERM'); });
50
- const address = server.address();
51
- return { server, url: `http://${host.includes(':') ? `[${host}]` : host}:${address.port}/` };
52
- }
53
- if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
54
- try {
55
- const { server, url } = await startDocumentationServer({ host: process.env.JSN_DOCS_HOST || '127.0.0.1', port: Number(process.env.JSN_DOCS_PORT || 0) });
56
- if (process.send) { process.send({ url, pid: process.pid }); process.disconnect(); }
57
- else process.stdout.write(`Documentation service listening at ${url}\n`);
58
- for (const signal of ['SIGTERM', 'SIGINT']) process.on(signal, () => { server.close(); });
59
- } catch (error) { process.stderr.write(error.message + '\n'); process.exitCode = 1; }
60
- }
@@ -1,126 +0,0 @@
1
- // Server-owned GitHub mirror and atomic FTS5 publication. Reuses the CLI ingester.
2
- import fs from 'node:fs';
3
- import path from 'node:path';
4
- import { fileURLToPath } from 'node:url';
5
- import { randomUUID } from 'node:crypto';
6
- import os from 'node:os';
7
- import { spawnSync } from 'node:child_process';
8
- import Database from 'better-sqlite3';
9
- import { ingestDocs } from './ingest.js';
10
- import { refreshDocs } from './refresh.js';
11
-
12
- const defaultStorage = path.join(process.env.JSN_DATA_HOME || path.join(os.homedir(), '.jsn'), 'docs-service');
13
- function git(args) {
14
- const result = spawnSync('git', args, { encoding: 'utf8', maxBuffer: 4 * 1024 * 1024, timeout: 15 * 60 * 1000 });
15
- if (result.status !== 0) throw new Error(`Git ${args[0]} failed: ${result.error?.message || result.stderr?.slice(-1000) || result.status}`);
16
- return result.stdout.trim();
17
- }
18
- function writeStatus(storage, status) {
19
- const temporary = path.join(storage, `status-${randomUUID()}.json`);
20
- fs.writeFileSync(temporary, JSON.stringify(status, null, 2) + '\n');
21
- fs.renameSync(temporary, path.join(storage, 'status.json'));
22
- }
23
- async function performSync(options = {}) {
24
- const storage = options.storage || process.env.DOCS_STORAGE_DIR || defaultStorage;
25
- const source = options.source || process.env.DOCS_SOURCE_URL || 'https://github.com/ServiceNow/ServiceNowDocs.git';
26
- const branch = options.branch || process.env.DOCS_SOURCE_BRANCH || 'australia';
27
- fs.mkdirSync(storage, { recursive: true });
28
- const repo = path.join(storage, 'source');
29
- const live = path.join(storage, 'docs.sqlite3');
30
- const staging = path.join(storage, `build-${randomUUID()}.sqlite3`);
31
- let previous = {};
32
- try { previous = JSON.parse(fs.readFileSync(path.join(storage, 'status.json'), 'utf8')); } catch { /* first run */ }
33
- // The shared service lock excludes concurrent publishers.
34
- for (const name of fs.readdirSync(storage)) {
35
- if (/^(build|clone)-[a-f0-9-]+(?:\.sqlite3(?:-wal|-shm)?)?$/.test(name)) {
36
- fs.rmSync(path.join(storage, name), { recursive: true, force: true });
37
- }
38
- }
39
- const startedAt = new Date().toISOString();
40
- writeStatus(storage, { ...previous, state: 'syncing', startedAt });
41
- try {
42
- if (!fs.existsSync(path.join(repo, '.git'))) {
43
- const cloning = path.join(storage, `clone-${randomUUID()}`);
44
- try {
45
- git(['clone', '--depth', '1', '--branch', branch, '--', source, cloning]);
46
- if (fs.existsSync(repo)) fs.rmSync(repo, { recursive: true, force: true });
47
- fs.renameSync(cloning, repo);
48
- } finally { fs.rmSync(cloning, { recursive: true, force: true }); }
49
- } else {
50
- // This clone is private to the service. Never operate on a developer's checkout.
51
- git(['-C', repo, 'fetch', '--depth', '1', 'origin', branch]);
52
- git(['-C', repo, 'reset', '--hard', 'FETCH_HEAD']);
53
- }
54
- const revision = git(['-C', repo, 'rev-parse', 'HEAD']);
55
- const markdown = path.join(repo, 'markdown');
56
- if (!fs.statSync(markdown).isDirectory()) throw new Error('Source has no markdown directory');
57
- let oldRevision;
58
- if (fs.existsSync(live)) {
59
- const db = new Database(live, { readonly: true });
60
- try {
61
- oldRevision = db.prepare("SELECT value FROM meta WHERE key = 'source_revision'").get()?.value;
62
- if (oldRevision !== revision || options.force) await db.backup(staging);
63
- } finally { db.close(); }
64
- }
65
- if (oldRevision === revision && !options.force) {
66
- const status = { ...previous, state: 'ready', revision, checkedAt: new Date().toISOString(), startedAt, error: null, changed: false };
67
- writeStatus(storage, status);
68
- return status;
69
- }
70
- const roots = [{ dir: markdown, prefix: '' }];
71
- const result = fs.existsSync(staging)
72
- ? refreshDocs({ roots, dbPath: staging })
73
- : ingestDocs({ roots, dbPath: staging, embed: false });
74
- if (result.errors) throw new Error(`Indexing skipped ${result.errors} documents; retaining the published index`);
75
- const db = new Database(staging);
76
- let count;
77
- try {
78
- count = db.prepare('SELECT COUNT(*) AS n FROM docs').get().n;
79
- if (!count) throw new Error('Refusing to publish an empty documentation index');
80
- if (db.pragma('quick_check', { simple: true }) !== 'ok') throw new Error('SQLite integrity check failed');
81
- db.exec("INSERT INTO docs_fts(docs_fts, rank) VALUES('integrity-check', 1)");
82
- const set = db.prepare('INSERT OR REPLACE INTO meta(key, value) VALUES(?, ?)');
83
- set.run('source_revision', revision);
84
- set.run('source_branch', branch);
85
- db.pragma('wal_checkpoint(TRUNCATE)');
86
- db.pragma('journal_mode = DELETE');
87
- } finally { db.close(); }
88
- fs.renameSync(staging, live);
89
- const status = { state: 'ready', revision, documents: count, startedAt, checkedAt: new Date().toISOString(), publishedAt: new Date().toISOString(), changed: true, error: null, result };
90
- writeStatus(storage, status);
91
- return status;
92
- } catch (error) {
93
- writeStatus(storage, { ...previous, state: 'failed', startedAt, checkedAt: new Date().toISOString(), error: error.message });
94
- throw error;
95
- } finally {
96
- for (const suffix of ['', '-wal', '-shm']) fs.rmSync(staging + suffix, { force: true });
97
- }
98
- }
99
- export async function syncDocumentation(options = {}) {
100
- const storage = options.storage || process.env.DOCS_STORAGE_DIR || defaultStorage;
101
- fs.mkdirSync(storage, { recursive: true });
102
- const lock = path.join(storage, 'sync-service.lock');
103
- try { fs.mkdirSync(lock); }
104
- catch (error) {
105
- if (error.code !== 'EEXIST') throw error;
106
- let pid;
107
- try { pid = Number(fs.readFileSync(path.join(lock, 'pid'), 'utf8')); } catch { /* another process may be writing it */ }
108
- if (!pid) {
109
- if (Date.now() - fs.statSync(lock).mtimeMs < 30_000) return { state: 'syncing', changed: false };
110
- fs.rmSync(lock, { recursive: true, force: true });
111
- return syncDocumentation(options);
112
- }
113
- try { process.kill(pid, 0); return { state: 'syncing', changed: false }; }
114
- catch (probe) { if (probe.code !== 'ESRCH') throw probe; }
115
- fs.rmSync(lock, { recursive: true });
116
- // Retry acquisition, so another waiting publisher still wins exclusively.
117
- return syncDocumentation(options);
118
- }
119
- fs.writeFileSync(path.join(lock, 'pid'), String(process.pid));
120
- try { return await performSync(options); }
121
- finally { fs.rmSync(lock, { recursive: true, force: true }); }
122
- }
123
- if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
124
- try { process.stdout.write(JSON.stringify(await syncDocumentation()) + '\n'); }
125
- catch (error) { process.stderr.write(error.message + '\n'); process.exitCode = 1; }
126
- }
@@ -1,57 +0,0 @@
1
- import * as prompts from './prompts.js';
2
- const { confirm, select, input } = prompts;
3
- import { ensureLocalDocumentation } from './commands/docs/local.js';
4
- import { saveConfig } from './config.js';
5
- import { docsServiceUrl, DEFAULT_DOCS_URL } from './commands/docs/client.js';
6
-
7
- export function connectionPreferences(config, existing = {}, flags = {}) {
8
- const saved = { read_only: false, skip_confirmations: false, include_counts: true };
9
- // Legacy profiles retain their historical defaults when a field is absent.
10
- const source = Object.keys(existing).length ? existing : (config.connectionDefaults || {});
11
- for (const key of Object.keys(saved)) if (typeof source[key] === 'boolean') saved[key] = source[key];
12
- for (const key of ['read_only', 'skip_confirmations', 'include_counts']) {
13
- const flag = key.replaceAll('_', '-');
14
- if (typeof flags[flag] === 'boolean') saved[key] = flags[flag];
15
- }
16
- return Object.fromEntries(['read_only', 'skip_confirmations', 'include_counts'].map(key => [key, Boolean(saved[key])]));
17
- }
18
-
19
- export async function askConnectionPreferences(defaults, prompts = { confirm }) {
20
- return {
21
- read_only: await prompts.confirm({ message: 'Read-only connections (block changes)?', default: defaults.read_only }),
22
- skip_confirmations: !(await prompts.confirm({ message: 'Confirm before deleting records?', default: !defaults.skip_confirmations })),
23
- include_counts: await prompts.confirm({ message: 'Include result totals on list commands?', default: defaults.include_counts }),
24
- };
25
- }
26
-
27
- export async function chooseConnectionPreferences(config, flags = {}, prompts = { confirm }) {
28
- const defaults = connectionPreferences(config, {}, flags);
29
- const summary = `Read-only: ${defaults.read_only ? 'yes' : 'no'} · Delete confirmations: ${defaults.skip_confirmations ? 'off' : 'on'} · Result totals: ${defaults.include_counts ? 'on' : 'off'}`;
30
- if (await prompts.confirm({ message: `${summary}\nUse these defaults for this connection?`, default: true })) return defaults;
31
- return askConnectionPreferences(defaults, prompts);
32
- }
33
-
34
- export async function configureDocumentation(config, prompts = { input, confirm }) {
35
- const current = config.docs || { source: 'hosted', url: DEFAULT_DOCS_URL };
36
- const hosted = await prompts.confirm({ message: 'Use JSN-hosted documentation?', default: current.source === 'hosted' });
37
- const next = { source: hosted ? 'hosted' : 'custom', url: DEFAULT_DOCS_URL };
38
- if (!hosted && await prompts.confirm({ message: 'Run a local documentation server for you?', default: current.source !== 'custom' })) {
39
- next.source = 'local';
40
- next.url = (await ensureLocalDocumentation()).url;
41
- } else if (!hosted) {
42
- next.url = await prompts.input({ message: 'Docs service base URL:', default: current.source === 'custom' ? current.url : 'http://127.0.0.1:3000',
43
- validate: value => { try { docsServiceUrl(value); return true; } catch (error) { return error.message; } } });
44
- next.url = docsServiceUrl(next.url);
45
- }
46
- config.docs = next;
47
- saveConfig(config);
48
- return next;
49
- }
50
-
51
- export async function configureGlobalDefaults(config, { documentation = true, prompts = { confirm, select, input } } = {}) {
52
- const preferences = await askConnectionPreferences(connectionPreferences(config), prompts);
53
- config.connectionDefaults = preferences;
54
- saveConfig(config);
55
- if (documentation) await configureDocumentation(config, prompts);
56
- return preferences;
57
- }