@jacebenson/jsn 4.5.1-dev.119.1 → 4.5.1-dev.120.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jacebenson/jsn",
3
- "version": "4.5.1-dev.119.1",
3
+ "version": "4.5.1-dev.120.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": {
@@ -0,0 +1,43 @@
1
+ // Publish a portable backup of the live service index, without re-ingesting docs.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { createHash } from 'node:crypto';
5
+ import { gzipSync } from 'node:zlib';
6
+ import Database from 'better-sqlite3';
7
+ import { validateDatabase, validateManifest } from './snapshot.js';
8
+
9
+ export async function publishServiceSnapshot(storage) {
10
+ const output = path.join(storage, 'snapshots');
11
+ fs.mkdirSync(output, { recursive: true });
12
+ const db = new Database(path.join(storage, 'docs.sqlite3'), { readonly: true, fileMustExist: true });
13
+ const temporary = fs.mkdtempSync(path.join(output, '.export-'));
14
+ try {
15
+ const revision = db.prepare("SELECT value FROM meta WHERE key='source_revision'").get()?.value;
16
+ if (!/^[a-f0-9]{7,64}$/.test(revision || '')) throw new Error('Index has no valid source revision');
17
+ try {
18
+ const cached = validateManifest(JSON.parse(fs.readFileSync(path.join(output, 'manifest.json'), 'utf8')));
19
+ if (cached.revision === revision && fs.existsSync(path.join(output, path.basename(cached.url)))) return cached;
20
+ } catch { /* no published snapshot yet */ }
21
+ const filename = path.join(temporary, 'docs.sqlite3');
22
+ await db.backup(filename);
23
+ const copy = new Database(filename);
24
+ try {
25
+ copy.prepare("INSERT OR REPLACE INTO meta(key,value) VALUES('snapshot_revision', ?)").run(revision);
26
+ copy.pragma('wal_checkpoint(TRUNCATE)');
27
+ copy.pragma('journal_mode = DELETE');
28
+ } finally { copy.close(); }
29
+ const documents = validateDatabase(filename);
30
+ const bytes = fs.readFileSync(filename);
31
+ const compressed = gzipSync(bytes);
32
+ const sha256 = createHash('sha256').update(compressed).digest('hex');
33
+ const name = `docs-${revision}-${sha256}.sqlite.gz`;
34
+ const manifest = validateManifest({ format: 1, schema: 1, cliCompatibility: 'docs-schema-1', revision,
35
+ documents, sha256, compressedBytes: compressed.length, databaseBytes: bytes.length,
36
+ builtAt: new Date().toISOString(), url: `https://jsn.jace.pro/docs-index/artifacts/${name}` });
37
+ fs.writeFileSync(path.join(temporary, name), compressed);
38
+ fs.renameSync(path.join(temporary, name), path.join(output, name));
39
+ fs.writeFileSync(path.join(temporary, 'manifest.json'), JSON.stringify(manifest) + '\n');
40
+ fs.renameSync(path.join(temporary, 'manifest.json'), path.join(output, 'manifest.json'));
41
+ return manifest;
42
+ } finally { db.close(); fs.rmSync(temporary, { recursive: true, force: true }); }
43
+ }
@@ -8,6 +8,8 @@ import { spawnSync } from 'node:child_process';
8
8
  import Database from 'better-sqlite3';
9
9
  import { ingestDocs } from './ingest.js';
10
10
  import { refreshDocs } from './refresh.js';
11
+ import { installSnapshot } from './snapshot.js';
12
+ import { publishServiceSnapshot } from './service-snapshot.js';
11
13
 
12
14
  const defaultStorage = path.join(process.env.JSN_DATA_HOME || path.join(os.homedir(), '.jsn'), 'docs-service');
13
15
  function git(args) {
@@ -39,6 +41,38 @@ async function performSync(options = {}) {
39
41
  const startedAt = new Date().toISOString();
40
42
  writeStatus(storage, { ...previous, state: 'syncing', startedAt });
41
43
  try {
44
+ // Only the first installation uses the hosted seed. Updates always use GitHub.
45
+ // Custom source repositories must never be seeded with an unrelated corpus.
46
+ if (!fs.existsSync(live) && ((!options.source && !process.env.DOCS_SOURCE_URL) || options.manifestURL) && branch === 'australia') {
47
+ try {
48
+ const seed = await installSnapshot({ dbPath: live,
49
+ manifestURL: options.manifestURL || process.env.DOCS_BOOTSTRAP_MANIFEST_URL,
50
+ fetchFn: options.fetchFn });
51
+ const db = new Database(live);
52
+ try {
53
+ db.prepare("INSERT OR REPLACE INTO meta(key,value) VALUES('source_revision', ?)").run(seed.revision);
54
+ db.prepare("INSERT OR REPLACE INTO meta(key,value) VALUES('source_branch', ?)").run(branch);
55
+ db.pragma('wal_checkpoint(TRUNCATE)'); db.pragma('journal_mode = DELETE');
56
+ } finally { db.close(); }
57
+ previous = { ...previous, revision: seed.revision, documents: seed.documents, seededFrom: 'snapshot' };
58
+ } catch (error) {
59
+ // An unavailable seed never prevents the original GitHub build path.
60
+ previous = { ...previous, bootstrapError: error.message };
61
+ }
62
+ }
63
+ if (!fs.existsSync(path.join(repo, '.git')) && fs.existsSync(live) && !options.force) {
64
+ const remote = git(['ls-remote', '--', source, `refs/heads/${branch}`]).split(/\s/)[0];
65
+ const db = new Database(live, { readonly: true });
66
+ let current;
67
+ try { current = db.prepare("SELECT value FROM meta WHERE key='source_revision'").get()?.value; }
68
+ finally { db.close(); }
69
+ if (remote && current === remote) {
70
+ await publishServiceSnapshot(storage);
71
+ const status = { ...previous, state: 'ready', revision: current, checkedAt: new Date().toISOString(), startedAt, error: null, changed: false };
72
+ writeStatus(storage, status);
73
+ return status;
74
+ }
75
+ }
42
76
  if (!fs.existsSync(path.join(repo, '.git'))) {
43
77
  const cloning = path.join(storage, `clone-${randomUUID()}`);
44
78
  try {
@@ -63,13 +97,14 @@ async function performSync(options = {}) {
63
97
  } finally { db.close(); }
64
98
  }
65
99
  if (oldRevision === revision && !options.force) {
100
+ await publishServiceSnapshot(storage);
66
101
  const status = { ...previous, state: 'ready', revision, checkedAt: new Date().toISOString(), startedAt, error: null, changed: false };
67
102
  writeStatus(storage, status);
68
103
  return status;
69
104
  }
70
105
  const roots = [{ dir: markdown, prefix: '' }];
71
106
  const result = fs.existsSync(staging)
72
- ? refreshDocs({ roots, dbPath: staging })
107
+ ? refreshDocs({ roots, dbPath: staging, sourceLeaseHeld: true })
73
108
  : ingestDocs({ roots, dbPath: staging, embed: false });
74
109
  if (result.errors) throw new Error(`Indexing skipped ${result.errors} documents; retaining the published index`);
75
110
  const db = new Database(staging);
@@ -86,6 +121,7 @@ async function performSync(options = {}) {
86
121
  db.pragma('journal_mode = DELETE');
87
122
  } finally { db.close(); }
88
123
  fs.renameSync(staging, live);
124
+ await publishServiceSnapshot(storage);
89
125
  const status = { state: 'ready', revision, documents: count, startedAt, checkedAt: new Date().toISOString(), publishedAt: new Date().toISOString(), changed: true, error: null, result };
90
126
  writeStatus(storage, status);
91
127
  return status;