@jacebenson/jsn 4.4.0-dev.115.1 → 4.5.0-dev.116.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.4.0-dev.115.1",
3
+ "version": "4.5.0-dev.116.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,117 @@
1
+ // FTS5 query sanitizing for the docs index.
2
+ //
3
+ // ServiceNow documentation is full of dotted, hyphenated and slash-separated
4
+ // identifiers (`com.snc.itsm.roles`, `glide.ui.escape_all_script`,
5
+ // `change-management`). FTS5 reads a bare `.`, `:`, `-`, `/` or `+` as query
6
+ // syntax and throws `fts5: syntax error`, so every token is rendered as a
7
+ // quoted phrase unless it is plain word characters. Uppercase AND/OR/NOT and a
8
+ // trailing `*` prefix keep working as operators.
9
+
10
+ const FTS_COLUMNS = new Set(['title', 'body']);
11
+ const BOOLEAN_OPERATORS = new Set(['AND', 'OR', 'NOT']);
12
+ const WORD = /^[\p{L}\p{N}_]+$/u;
13
+
14
+ function quotePhrase(text) {
15
+ return `"${text.replace(/"/g, '""')}"`;
16
+ }
17
+
18
+ function renderValue(value, prefix) {
19
+ const rendered = WORD.test(value) ? value : quotePhrase(value);
20
+ return prefix ? `${rendered}*` : rendered;
21
+ }
22
+
23
+ function renderTerm(text) {
24
+ let prefix = false;
25
+ let core = text;
26
+ while (core.endsWith('*')) {
27
+ prefix = true;
28
+ core = core.slice(0, -1);
29
+ }
30
+ if (!core) return null;
31
+
32
+ const separator = core.indexOf(':');
33
+ if (separator > 0) {
34
+ const column = core.slice(0, separator);
35
+ const rest = core.slice(separator + 1);
36
+ if (FTS_COLUMNS.has(column) && rest) {
37
+ return `${column}: ${renderValue(rest, prefix)}`;
38
+ }
39
+ }
40
+ return renderValue(core, prefix);
41
+ }
42
+
43
+ function splitTokens(input) {
44
+ const tokens = [];
45
+ let i = 0;
46
+ while (i < input.length) {
47
+ const ch = input[i];
48
+ if (/\s/.test(ch)) {
49
+ i += 1;
50
+ continue;
51
+ }
52
+ if (ch === '"') {
53
+ let j = i + 1;
54
+ let text = '';
55
+ while (j < input.length) {
56
+ if (input[j] === '"') {
57
+ if (input[j + 1] === '"') {
58
+ text += '"';
59
+ j += 2;
60
+ continue;
61
+ }
62
+ j += 1;
63
+ break;
64
+ }
65
+ text += input[j];
66
+ j += 1;
67
+ }
68
+ let prefix = false;
69
+ if (input[j] === '*') {
70
+ prefix = true;
71
+ j += 1;
72
+ }
73
+ tokens.push({ kind: 'phrase', text, prefix });
74
+ i = j;
75
+ continue;
76
+ }
77
+ let j = i;
78
+ while (j < input.length && !/\s/.test(input[j])) j += 1;
79
+ tokens.push({ kind: 'term', text: input.slice(i, j) });
80
+ i = j;
81
+ }
82
+ return tokens;
83
+ }
84
+
85
+ /**
86
+ * Turn a free-text search query into an FTS5 MATCH expression that cannot throw
87
+ * a syntax error on punctuation. Returns '' when nothing searchable is left.
88
+ */
89
+ export function sanitizeFts5Query(query) {
90
+ const raw = query == null ? '' : String(query);
91
+ const out = [];
92
+
93
+ for (const token of splitTokens(raw)) {
94
+ if (token.kind === 'phrase') {
95
+ out.push({ text: quotePhrase(token.text) + (token.prefix ? '*' : '') });
96
+ continue;
97
+ }
98
+ if (BOOLEAN_OPERATORS.has(token.text)) {
99
+ // Operators only mean something between two operands.
100
+ if (out.length === 0) continue;
101
+ if (out[out.length - 1].operator) {
102
+ // FTS5 only accepts NOT as an infix operator, so "a AND NOT b" becomes "a NOT b".
103
+ if (token.text === 'NOT' && out[out.length - 1].text !== 'NOT') {
104
+ out[out.length - 1] = { text: 'NOT', operator: true };
105
+ }
106
+ continue;
107
+ }
108
+ out.push({ text: token.text, operator: true });
109
+ continue;
110
+ }
111
+ const rendered = renderTerm(token.text);
112
+ if (rendered) out.push({ text: rendered });
113
+ }
114
+
115
+ while (out.length > 0 && out[out.length - 1].operator) out.pop();
116
+ return out.map((token) => token.text).join(' ');
117
+ }
@@ -2,6 +2,7 @@
2
2
 
3
3
  import fs from 'node:fs';
4
4
  import { getDocsDbPath, hasEmbeddings, openDocsDb, closeDocsDb, withDocsDb, getMeta } from './db.js';
5
+ import { sanitizeFts5Query } from './fts.js';
5
6
  import { encodeText, similarity, bytesToPhases, DEFAULT_DIM } from './hrr.js';
6
7
 
7
8
  function safeParse(s) {
@@ -28,9 +29,12 @@ export function getDocByIdOrPath(idOrPath, opts = {}) {
28
29
  } else {
29
30
  row = db.prepare('SELECT * FROM docs WHERE path LIKE ?').get(`%${idOrPath}%`);
30
31
  if (!row) {
31
- row = db.prepare(
32
- `SELECT d.* FROM docs_fts JOIN docs d ON d.id = docs_fts.rowid WHERE docs_fts MATCH ? LIMIT 1`
33
- ).get(idOrPath);
32
+ const ftsQuery = sanitizeFts5Query(idOrPath);
33
+ if (ftsQuery) {
34
+ row = db.prepare(
35
+ `SELECT d.* FROM docs_fts JOIN docs d ON d.id = docs_fts.rowid WHERE docs_fts MATCH ? LIMIT 1`
36
+ ).get(ftsQuery);
37
+ }
34
38
  }
35
39
  }
36
40
  return row;
@@ -58,8 +62,13 @@ export function searchDocs(opts = {}) {
58
62
  const mode = opts.mode === 'keyword' ? 'keyword' : 'hybrid';
59
63
  const useHybrid = mode === 'hybrid' && hasEmbeddings(db);
60
64
 
65
+ const ftsQuery = sanitizeFts5Query(q);
66
+ if (!ftsQuery) {
67
+ return { query: q, mode: useHybrid ? 'hybrid' : 'keyword', total: 0, count: 0, results: [] };
68
+ }
69
+
61
70
  const filters = [];
62
- const params = { q, limit, offset };
71
+ const params = { q: ftsQuery, limit, offset };
63
72
  if (bundle) {
64
73
  filters.push('d.bundle = @bundle');
65
74
  params.bundle = bundle;
@@ -73,7 +82,7 @@ export function searchDocs(opts = {}) {
73
82
  // Total matching docs (for pagination)
74
83
  const total = db
75
84
  .prepare(`SELECT COUNT(*) AS n FROM docs_fts JOIN docs d ON d.id = docs_fts.rowid WHERE docs_fts MATCH @q${where}`)
76
- .get({ q, ...(bundle && { bundle }), ...(docType && { docType }) }).n;
85
+ .get({ q: ftsQuery, ...(bundle && { bundle }), ...(docType && { docType }) }).n;
77
86
 
78
87
  let rows;
79
88
  if (!useHybrid) {
@@ -91,7 +100,7 @@ export function searchDocs(opts = {}) {
91
100
  )
92
101
  .all(params);
93
102
  } else {
94
- const candParams = { q, cand: (limit + offset) * 4 + 20 };
103
+ const candParams = { q: ftsQuery, cand: (limit + offset) * 4 + 20 };
95
104
  if (bundle) candParams.bundle = bundle;
96
105
  if (docType) candParams.docType = docType;
97
106
  const candidates = db
@@ -6,6 +6,7 @@ import http from 'node:http';
6
6
  import { URL } from 'node:url';
7
7
  import Database from 'better-sqlite3';
8
8
  import { getDocsDbPath, hasEmbeddings, closeDocsDb } from './db.js';
9
+ import { sanitizeFts5Query } from './fts.js';
9
10
  import { encodeText, similarity, bytesToPhases, DEFAULT_DIM } from './hrr.js';
10
11
 
11
12
  const PUBLIC_DIR = path.join(import.meta.dirname, 'public');
@@ -115,8 +116,13 @@ export function serveDocs(opts = {}) {
115
116
  let mode = (url.searchParams.get('mode') || (hasEmb ? 'hybrid' : 'keyword')).toString();
116
117
  if (mode === 'hybrid' && !hasEmb) mode = 'keyword';
117
118
 
119
+ const ftsQuery = sanitizeFts5Query(q);
120
+ if (!ftsQuery) {
121
+ return sendJSON(res, 200, { query: q, mode, count: 0, results: [] });
122
+ }
123
+
118
124
  const filters = [];
119
- const params = { q, limit, offset };
125
+ const params = { q: ftsQuery, limit, offset };
120
126
  if (bundle) {
121
127
  filters.push('d.bundle = @bundle');
122
128
  params.bundle = bundle;
@@ -145,7 +151,7 @@ export function serveDocs(opts = {}) {
145
151
  return sendJSON(res, 200, { query: q, mode, count: rows.length, results: rows });
146
152
  }
147
153
 
148
- const candParams = { q, cand: (limit + offset) * 4 + 20 };
154
+ const candParams = { q: ftsQuery, cand: (limit + offset) * 4 + 20 };
149
155
  if (bundle) candParams.bundle = bundle;
150
156
  if (docType) candParams.docType = docType;
151
157
  const candidates = db