@jacebenson/jsn 4.5.1 → 5.0.0-dev.121.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.
@@ -1,300 +1,84 @@
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';
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';
7
5
  import { declareCapabilities } from '../../capabilities.js';
8
- import { formatCommandList } from '../../helpers.js';
6
+ import { AppError } from '../../errors.js';
9
7
 
10
8
  declareCapabilities('docs', { noInstance: true, skipDailyChecks: true });
11
9
 
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`;
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}` });
17
34
  }
18
35
 
19
36
  export function docsCmd(wrap) {
20
37
  return {
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
- },
282
- handler: wrap(async (argv, app) => {
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'),
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'] }));
297
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
+ }) }),
68
+ 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 → Defaults and documentation.\nNo ServiceNow connection is needed. Hosted mode downloads no database.\n`,
298
82
  }, { summary });
299
83
  }),
300
84
  };
@@ -0,0 +1,15 @@
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(); }
@@ -0,0 +1,81 @@
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
+ }
@@ -0,0 +1,68 @@
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
+ }
@@ -0,0 +1,60 @@
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
+ }