@lizimin/dsh-session-search 0.0.0-stage → 1.3.7
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/CHANGELOG.md +122 -0
- package/LICENSE +21 -0
- package/README.md +155 -2
- package/README.zh-CN.md +154 -0
- package/client.js +1013 -0
- package/cordis.patch.yml +3 -0
- package/docs/community-listing.yml +6 -0
- package/icon.svg +1 -0
- package/index.js +111 -0
- package/locale/en.json +1 -0
- package/locale/zh.json +1 -0
- package/package.json +66 -4
- package/search.js +454 -0
- package/session-catalog.js +136 -0
- package/settings.js +42 -0
package/search.js
ADDED
|
@@ -0,0 +1,454 @@
|
|
|
1
|
+
import {createHash} from 'node:crypto';
|
|
2
|
+
import {Script} from 'node:vm';
|
|
3
|
+
import {catalog, finalDocuments, processDocuments, LIMIT} from './session-catalog.js';
|
|
4
|
+
export {catalog, workspaceCatalog, finalDocuments, processDocuments, workspaceSnapshot, LIMIT, UNGROUPED_WORKSPACE_ID} from './session-catalog.js';
|
|
5
|
+
|
|
6
|
+
export const MATCH_TIMEOUT_MS = 100;
|
|
7
|
+
export const MAX_SNIPPET = 640;
|
|
8
|
+
export const MAX_RANGES = 64;
|
|
9
|
+
export const MAX_HIGHLIGHT_TEXTS = 500;
|
|
10
|
+
export const MAX_HIGHLIGHT_TEXT = 200000;
|
|
11
|
+
export const MAX_HIGHLIGHT_RANGES = 256;
|
|
12
|
+
export const MAX_HIGHLIGHT_TOTAL_RANGES = 2048;
|
|
13
|
+
const digest = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
|
14
|
+
function string(value, name, max = 1024) {
|
|
15
|
+
if (typeof value !== 'string' || !value.trim() || value.length > max) throw new Error(`${name} must be nonempty text of at most ${max} characters`);
|
|
16
|
+
return value;
|
|
17
|
+
}
|
|
18
|
+
function selection(input, singular, plural, max) {
|
|
19
|
+
let values = input[plural];
|
|
20
|
+
if (typeof values === 'string') {
|
|
21
|
+
try {values = JSON.parse(values);} catch {throw new Error(`${plural} must be an array or JSON array string`);}
|
|
22
|
+
}
|
|
23
|
+
if (values === undefined) values = [];
|
|
24
|
+
if (!Array.isArray(values) || values.length > max) throw new Error(`${plural} must be an array of at most ${max} IDs`);
|
|
25
|
+
values = Array.from(values, value => string(value, plural, 512));
|
|
26
|
+
if (input[singular] !== undefined) {
|
|
27
|
+
const legacy = string(input[singular], singular, 512);
|
|
28
|
+
if (values.length) throw new Error(`${singular} cannot be combined with nonempty ${plural}`);
|
|
29
|
+
values = [legacy];
|
|
30
|
+
}
|
|
31
|
+
return [...new Set(values)].sort();
|
|
32
|
+
}
|
|
33
|
+
const MAX_DATE_MS = 8640000000000000;
|
|
34
|
+
function timestamp(value, name) {
|
|
35
|
+
if (value === undefined) return undefined;
|
|
36
|
+
if (typeof value === 'string' && /^[+-]?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/iu.test(value)) value = Number(value);
|
|
37
|
+
if (typeof value !== 'number' || !Number.isSafeInteger(value) || Math.abs(value) > MAX_DATE_MS) {
|
|
38
|
+
throw new Error(`${name} must be a finite safe integer Unix epoch millisecond timestamp within the JavaScript Date range`);
|
|
39
|
+
}
|
|
40
|
+
return value;
|
|
41
|
+
}
|
|
42
|
+
function flag(value, name) {
|
|
43
|
+
if (value === undefined || value === false || value === 'false') return false;
|
|
44
|
+
if (value === true || value === 'true') return true;
|
|
45
|
+
throw new Error(`${name} must be a boolean`);
|
|
46
|
+
}
|
|
47
|
+
function choice(value, fallback, values, name) {
|
|
48
|
+
const result = value ?? fallback;
|
|
49
|
+
if (!values.includes(result)) throw new Error(`Invalid ${name}`);
|
|
50
|
+
return result;
|
|
51
|
+
}
|
|
52
|
+
export class SearchMatchError extends Error {
|
|
53
|
+
constructor(message, code) {super(message); this.name = 'SearchMatchError'; this.code = code;}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// Pattern compilation and both matchers run INSIDE the timed VM, including
|
|
57
|
+
// iteration, snippet construction and serialization. User input is data only;
|
|
58
|
+
// it is never interpolated into JavaScript source or evaluated as JavaScript.
|
|
59
|
+
function compileMatchPattern(spec) {
|
|
60
|
+
const source = spec.useRegex ? spec.query : spec.query.trim().split(/\s+/u)
|
|
61
|
+
.map(part => part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('\\s+');
|
|
62
|
+
// Noncapturing wrapping preserves numbered backreferences. Putting boundaries
|
|
63
|
+
// in the pattern permits alternatives/backtracking to find a whole match.
|
|
64
|
+
const flags = spec.matchCase ? 'gu' : 'giu';
|
|
65
|
+
// Validate the source in its own right: an unmatched parenthesis must not
|
|
66
|
+
// become valid by accidentally closing our whole-word wrapper.
|
|
67
|
+
const rawPattern = new RegExp(source, flags);
|
|
68
|
+
const bounded = spec.wholeWord ? `(?<![\\p{L}\\p{N}_])(?:${source})(?![\\p{L}\\p{N}_])` : source;
|
|
69
|
+
return spec.wholeWord ? new RegExp(bounded, flags) : rawPattern;
|
|
70
|
+
}
|
|
71
|
+
function matchDocumentList(documents, spec, maxSnippet, maxRanges, fullDocument) {
|
|
72
|
+
const pattern = compileMatchPattern(spec);
|
|
73
|
+
const hits = [];
|
|
74
|
+
let totalRanges = 0, truncated = false;
|
|
75
|
+
for (const doc of documents) {
|
|
76
|
+
if (fullDocument && totalRanges >= fullDocument.maxTotalRanges) {truncated = true; break;}
|
|
77
|
+
const text = doc.text;
|
|
78
|
+
pattern.lastIndex = 0;
|
|
79
|
+
let match = pattern.exec(text);
|
|
80
|
+
if (!match) continue;
|
|
81
|
+
let start = fullDocument ? 0 : Math.max(0, match.index - 100);
|
|
82
|
+
// Keep snippet edges between code points, while offsets remain UTF-16.
|
|
83
|
+
if (start > 0 && /[\uDC00-\uDFFF]/u.test(text[start]) && /[\uD800-\uDBFF]/u.test(text[start - 1])) start--;
|
|
84
|
+
let end = fullDocument ? text.length : Math.min(text.length, start + Math.min(maxSnippet - 2, Math.max(360, match[0].length + 140)));
|
|
85
|
+
if (end < text.length && /[\uDC00-\uDFFF]/u.test(text[end]) && /[\uD800-\uDBFF]/u.test(text[end - 1])) end--;
|
|
86
|
+
const prefix = start ? '…' : '';
|
|
87
|
+
const ranges = [];
|
|
88
|
+
const rangeLimit = fullDocument ? Math.min(maxRanges, fullDocument.maxTotalRanges - totalRanges) : maxRanges;
|
|
89
|
+
let rangesTruncated = false;
|
|
90
|
+
do {
|
|
91
|
+
const from = match.index;
|
|
92
|
+
const to = from + match[0].length;
|
|
93
|
+
if (from > end || (from === end && to !== from)) break;
|
|
94
|
+
if (to >= start) {
|
|
95
|
+
if (fullDocument && ranges.length >= rangeLimit) {rangesTruncated = true; break;}
|
|
96
|
+
ranges.push({start: Math.max(start, from) - start + prefix.length, end: Math.min(end, to) - start + prefix.length});
|
|
97
|
+
if (to > end) rangesTruncated = true;
|
|
98
|
+
}
|
|
99
|
+
// Only the highlight list is capped; the document itself is still a hit.
|
|
100
|
+
if (!fullDocument && ranges.length >= rangeLimit) {rangesTruncated = true; break;}
|
|
101
|
+
if (!match[0].length) {
|
|
102
|
+
if (pattern.lastIndex >= text.length) break;
|
|
103
|
+
pattern.lastIndex += text.codePointAt(pattern.lastIndex) > 0xffff ? 2 : 1;
|
|
104
|
+
}
|
|
105
|
+
if (pattern.lastIndex > end) break;
|
|
106
|
+
// Always match against the original full text, never a sliced snippet:
|
|
107
|
+
// anchors, lookbehind/lookahead and whole-word context must stay intact.
|
|
108
|
+
match = pattern.exec(text);
|
|
109
|
+
} while (match);
|
|
110
|
+
if (fullDocument) {
|
|
111
|
+
totalRanges += ranges.length;
|
|
112
|
+
if (rangesTruncated) truncated = true;
|
|
113
|
+
hits.push({index: doc.index, ranges, ...(rangesTruncated ? {rangesTruncated: true} : {})});
|
|
114
|
+
} else hits.push({seq: doc.seq, time: doc.time, type: doc.type,
|
|
115
|
+
snippet: prefix + text.slice(start, end) + (end < text.length ? '…' : ''), ranges,
|
|
116
|
+
...(rangesTruncated ? {rangesTruncated: true} : {})});
|
|
117
|
+
}
|
|
118
|
+
return JSON.stringify(fullDocument ? {items: hits, ...(truncated ? {truncated: true} : {})} : hits);
|
|
119
|
+
}
|
|
120
|
+
// All helpers, the full-document literal presence scan, candidate scans, DP,
|
|
121
|
+
// and snippet work run within the SAME per-session VM deadline; none run in the
|
|
122
|
+
// service/catalog loop. Literal presence is independent of fuzzy candidates:
|
|
123
|
+
// exact substrings can exist even when a whole candidate word is not a fuzzy hit.
|
|
124
|
+
function matchFuzzyDocumentList(documents, spec, maxSnippet, maxRanges, fullDocument) {
|
|
125
|
+
const exactPattern = compileMatchPattern(spec);
|
|
126
|
+
let hasExactMatches = false;
|
|
127
|
+
if (!fullDocument) for (const doc of documents) {
|
|
128
|
+
exactPattern.lastIndex = 0;
|
|
129
|
+
if (exactPattern.test(doc.text)) {hasExactMatches = true; break;}
|
|
130
|
+
}
|
|
131
|
+
const wordCharacter = /[\p{L}\p{N}_]/u;
|
|
132
|
+
const wordAt = /[\p{L}\p{N}_]+/uy;
|
|
133
|
+
const spaceAt = /\s+/uy;
|
|
134
|
+
const characters = new Map();
|
|
135
|
+
function comparable(character) {
|
|
136
|
+
if (spec.matchCase) return candidate => candidate === character;
|
|
137
|
+
// Unicode simple case folding, like the exact /iu branch. Folding a whole
|
|
138
|
+
// string with toLowerCase() can expand İ and corrupt both matching/offsets.
|
|
139
|
+
if (!characters.has(character)) {
|
|
140
|
+
const escaped = character.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
141
|
+
const pattern = new RegExp(`^(?:${escaped})$`, 'iu');
|
|
142
|
+
characters.set(character, candidate => pattern.test(candidate));
|
|
143
|
+
}
|
|
144
|
+
return characters.get(character);
|
|
145
|
+
}
|
|
146
|
+
const tokens = Array.from(spec.query.trim().matchAll(/[\p{L}\p{N}_]+|\s+|[^\p{L}\p{N}_\s]/gu), match => {
|
|
147
|
+
const value = match[0];
|
|
148
|
+
if (/^\s/u.test(value)) return {kind: 'space'};
|
|
149
|
+
if (!wordCharacter.test(value)) return {kind: 'literal', value};
|
|
150
|
+
const points = Array.from(value);
|
|
151
|
+
return {kind: 'word', length: points.length, equal: points.map(comparable),
|
|
152
|
+
edits: points.length <= 3 ? 0 : points.length <= 7 ? 1 : 2};
|
|
153
|
+
});
|
|
154
|
+
function wordMatch(token, value, offset) {
|
|
155
|
+
const limit = spec.fuzzy === 'typo' ? token.length + token.edits : 4 * token.length + 8;
|
|
156
|
+
// Reject enormous candidate words before allocating a code-point array.
|
|
157
|
+
if (value.length > 2 * limit) return null;
|
|
158
|
+
const points = Array.from(value);
|
|
159
|
+
if (points.length > limit) return null;
|
|
160
|
+
if (spec.fuzzy === 'subsequence') {
|
|
161
|
+
// Latest starts for each query prefix find the tightest window in O(n*m).
|
|
162
|
+
// Descending updates ensure repeated query letters consume distinct points.
|
|
163
|
+
const starts = new Array(token.length).fill(-1);
|
|
164
|
+
let bestStart = -1, bestEnd = -1;
|
|
165
|
+
for (let i = 0; i < points.length; i++) {
|
|
166
|
+
for (let k = Math.min(i, token.length - 1); k >= 0; k--) {
|
|
167
|
+
if (!token.equal[k](points[i]) || (k > 0 && starts[k - 1] < 0)) continue;
|
|
168
|
+
starts[k] = k === 0 ? i : starts[k - 1];
|
|
169
|
+
if (k === token.length - 1 && (bestStart < 0 || i - starts[k] < bestEnd - bestStart)) {
|
|
170
|
+
bestStart = starts[k]; bestEnd = i;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
if (bestStart < 0) return null;
|
|
175
|
+
const positions = [];
|
|
176
|
+
let position = offset;
|
|
177
|
+
for (const point of points) {positions.push(position); position += point.length;}
|
|
178
|
+
const ranges = [];
|
|
179
|
+
for (let i = bestEnd, k = token.length - 1; k >= 0; i--) {
|
|
180
|
+
if (token.equal[k](points[i])) {
|
|
181
|
+
ranges.push({start: positions[i], end: positions[i] + points[i].length}); k--;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
return ranges.reverse();
|
|
185
|
+
}
|
|
186
|
+
const m = token.length, n = points.length, bound = token.edits;
|
|
187
|
+
if (Math.abs(m - n) > bound) return null;
|
|
188
|
+
if (m === n && points.every((point, index) => token.equal[index](point))) return [{start: offset, end: offset + value.length}];
|
|
189
|
+
if (!bound) return null;
|
|
190
|
+
// Banded optimal-string-alignment DP, not unrestricted Damerau distance.
|
|
191
|
+
// Each row needs its predecessor and the row before it for one adjacent
|
|
192
|
+
// transposition; the length bound and band keep work bounded per word.
|
|
193
|
+
const infinity = bound + 1;
|
|
194
|
+
let older, previous = Array.from({length: n + 1}, (_, j) => j <= bound ? j : infinity);
|
|
195
|
+
for (let i = 1; i <= m; i++) {
|
|
196
|
+
const current = new Array(n + 1).fill(infinity);
|
|
197
|
+
if (i <= bound) current[0] = i;
|
|
198
|
+
for (let j = Math.max(1, i - bound); j <= Math.min(n, i + bound); j++) {
|
|
199
|
+
current[j] = Math.min(previous[j] + 1, current[j - 1] + 1,
|
|
200
|
+
previous[j - 1] + (token.equal[i - 1](points[j - 1]) ? 0 : 1));
|
|
201
|
+
if (i > 1 && j > 1 && token.equal[i - 1](points[j - 2]) && token.equal[i - 2](points[j - 1])) {
|
|
202
|
+
current[j] = Math.min(current[j], older[j - 2] + 1);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
older = previous;
|
|
206
|
+
previous = current;
|
|
207
|
+
}
|
|
208
|
+
return previous[n] <= bound ? [{start: offset, end: offset + value.length}] : null;
|
|
209
|
+
}
|
|
210
|
+
function before(text, offset) {
|
|
211
|
+
if (!offset) return '';
|
|
212
|
+
const last = text.charCodeAt(offset - 1);
|
|
213
|
+
return text.slice(offset - (last >= 0xdc00 && last <= 0xdfff && offset > 1 &&
|
|
214
|
+
text.charCodeAt(offset - 2) >= 0xd800 && text.charCodeAt(offset - 2) <= 0xdbff ? 2 : 1), offset);
|
|
215
|
+
}
|
|
216
|
+
function matchAt(text, start) {
|
|
217
|
+
if (spec.wholeWord && wordCharacter.test(before(text, start))) return null;
|
|
218
|
+
let offset = start;
|
|
219
|
+
const ranges = [];
|
|
220
|
+
for (const token of tokens) {
|
|
221
|
+
if (token.kind === 'word') {
|
|
222
|
+
wordAt.lastIndex = offset;
|
|
223
|
+
const candidate = wordAt.exec(text);
|
|
224
|
+
if (!candidate) return null;
|
|
225
|
+
const selected = wordMatch(token, candidate[0], offset);
|
|
226
|
+
if (!selected) return null;
|
|
227
|
+
ranges.push(...selected);
|
|
228
|
+
offset = wordAt.lastIndex;
|
|
229
|
+
} else if (token.kind === 'space') {
|
|
230
|
+
spaceAt.lastIndex = offset;
|
|
231
|
+
const candidate = spaceAt.exec(text);
|
|
232
|
+
if (!candidate) return null;
|
|
233
|
+
ranges.push({start: offset, end: spaceAt.lastIndex});
|
|
234
|
+
offset = spaceAt.lastIndex;
|
|
235
|
+
} else {
|
|
236
|
+
if (!text.startsWith(token.value, offset)) return null;
|
|
237
|
+
ranges.push({start: offset, end: offset + token.value.length});
|
|
238
|
+
offset += token.value.length;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
if (spec.wholeWord && offset < text.length && wordCharacter.test(String.fromCodePoint(text.codePointAt(offset)))) return null;
|
|
242
|
+
return {start, end: offset, ranges};
|
|
243
|
+
}
|
|
244
|
+
const hits = [];
|
|
245
|
+
let totalRanges = 0, truncated = false;
|
|
246
|
+
for (const doc of documents) {
|
|
247
|
+
if (fullDocument && totalRanges >= fullDocument.maxTotalRanges) {truncated = true; break;}
|
|
248
|
+
const text = doc.text;
|
|
249
|
+
// Streaming tokens avoid storing the entire document or searching arbitrary
|
|
250
|
+
// substrings of a candidate word. Punctuation can start at any code point.
|
|
251
|
+
const candidates = /[\p{L}\p{N}_]+|[^\p{L}\p{N}_]/gu;
|
|
252
|
+
let candidate, first, start, end, prefix;
|
|
253
|
+
const ranges = [];
|
|
254
|
+
const rangeLimit = fullDocument ? Math.min(maxRanges, fullDocument.maxTotalRanges - totalRanges) : maxRanges;
|
|
255
|
+
let rangesTruncated = false;
|
|
256
|
+
while ((candidate = candidates.exec(text))) {
|
|
257
|
+
if (first && candidate.index >= end) break;
|
|
258
|
+
const match = matchAt(text, candidate.index);
|
|
259
|
+
if (!match) continue;
|
|
260
|
+
if (!first) {
|
|
261
|
+
first = match;
|
|
262
|
+
start = fullDocument ? 0 : Math.max(0, match.start - 100);
|
|
263
|
+
if (start > 0 && /[\uDC00-\uDFFF]/u.test(text[start]) && /[\uD800-\uDBFF]/u.test(text[start - 1])) start--;
|
|
264
|
+
end = fullDocument ? text.length : Math.min(text.length, start + Math.min(maxSnippet - 2, Math.max(360, match.end - match.start + 140)));
|
|
265
|
+
if (end < text.length && /[\uDC00-\uDFFF]/u.test(text[end]) && /[\uD800-\uDBFF]/u.test(text[end - 1])) end--;
|
|
266
|
+
prefix = start ? '…' : '';
|
|
267
|
+
}
|
|
268
|
+
// Merge touching highlights: typo highlights complete words, subsequence
|
|
269
|
+
// highlights selected code points only; literal separators stay visible.
|
|
270
|
+
for (const range of match.ranges) {
|
|
271
|
+
if (range.start >= end) {rangesTruncated = true; break;}
|
|
272
|
+
if (range.end > end) rangesTruncated = true;
|
|
273
|
+
const from = Math.max(start, range.start) - start + prefix.length;
|
|
274
|
+
const to = Math.min(end, range.end) - start + prefix.length;
|
|
275
|
+
const last = ranges[ranges.length - 1];
|
|
276
|
+
if (last && last.end === from) last.end = to;
|
|
277
|
+
else if (ranges.length < rangeLimit) ranges.push({start: from, end: to});
|
|
278
|
+
else {rangesTruncated = true; break;}
|
|
279
|
+
}
|
|
280
|
+
// Highlight caps do not affect whether the document is counted as a hit.
|
|
281
|
+
if (rangesTruncated || (!fullDocument && ranges.length >= rangeLimit)) {rangesTruncated = true; break;}
|
|
282
|
+
candidates.lastIndex = match.end;
|
|
283
|
+
}
|
|
284
|
+
if (first) {
|
|
285
|
+
if (fullDocument) {
|
|
286
|
+
totalRanges += ranges.length;
|
|
287
|
+
if (rangesTruncated) truncated = true;
|
|
288
|
+
hits.push({index: doc.index, ranges, ...(rangesTruncated ? {rangesTruncated: true} : {})});
|
|
289
|
+
} else hits.push({seq: doc.seq, time: doc.time, type: doc.type,
|
|
290
|
+
snippet: prefix + text.slice(start, end) + (end < text.length ? '…' : ''), ranges,
|
|
291
|
+
...(rangesTruncated ? {rangesTruncated: true} : {})});
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
return JSON.stringify(fullDocument ? {items: hits, ...(truncated ? {truncated: true} : {})} : {hits, hasExactMatches});
|
|
295
|
+
}
|
|
296
|
+
const matchingScript = new Script(`${compileMatchPattern.toString()}\n(${matchDocumentList.toString()})(documents, spec, maxSnippet, maxRanges, fullDocument)`, {filename: 'session-search-matcher-v1.7.vm.js'});
|
|
297
|
+
const fuzzyMatchingScript = new Script(`${compileMatchPattern.toString()}\n(${matchFuzzyDocumentList.toString()})(documents, spec, maxSnippet, maxRanges, fullDocument)`, {filename: 'session-search-fuzzy-v1.7.vm.js'});
|
|
298
|
+
function matchDocuments(documents, spec, fullDocument) {
|
|
299
|
+
try {
|
|
300
|
+
// One deadline covers the complete per-session document list, NOT one
|
|
301
|
+
// budget per candidate or exec call. No regex executes outside this VM.
|
|
302
|
+
const script = spec.fuzzy === 'off' ? matchingScript : fuzzyMatchingScript;
|
|
303
|
+
return JSON.parse(script.runInNewContext({documents, spec, fullDocument, maxSnippet: MAX_SNIPPET,
|
|
304
|
+
maxRanges: fullDocument ? MAX_HIGHLIGHT_RANGES : MAX_RANGES},
|
|
305
|
+
{timeout: MATCH_TIMEOUT_MS, contextCodeGeneration: {strings: false, wasm: false}}));
|
|
306
|
+
} catch (error) {
|
|
307
|
+
if (error?.code === 'ERR_SCRIPT_EXECUTION_TIMEOUT') {
|
|
308
|
+
throw new SearchMatchError(`Search matching timed out after ${MATCH_TIMEOUT_MS}ms for ${fullDocument ? 'the highlight batch' : 'one session'}. Simplify the expression or narrow the scope. No partial results returned.`, 'SEARCH_MATCH_TIMEOUT');
|
|
309
|
+
}
|
|
310
|
+
if (error?.name === 'SyntaxError') throw new SearchMatchError(`Invalid regular expression: ${error.message}`, 'INVALID_REGEX');
|
|
311
|
+
throw new SearchMatchError(`Search matching failed: ${error instanceof Error ? error.message : String(error)}`, 'SEARCH_MATCH_FAILED');
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function matchOptions(input) {
|
|
316
|
+
const matchCase = flag(input.matchCase, 'matchCase');
|
|
317
|
+
const wholeWord = flag(input.wholeWord, 'wholeWord');
|
|
318
|
+
const useRegex = flag(input.useRegex, 'useRegex');
|
|
319
|
+
if (input.fuzzy === null) throw new Error('Invalid fuzzy mode');
|
|
320
|
+
const fuzzy = choice(input.fuzzy, 'off', ['off', 'typo', 'subsequence'], 'fuzzy mode');
|
|
321
|
+
if (useRegex && fuzzy !== 'off') throw new Error('useRegex cannot be combined with fuzzy matching. Set fuzzy to off.');
|
|
322
|
+
return {matchCase, wholeWord, useRegex, fuzzy};
|
|
323
|
+
}
|
|
324
|
+
function matchQuery(value, fuzzy) {
|
|
325
|
+
const query = string(value, 'query');
|
|
326
|
+
if (fuzzy !== 'off') {
|
|
327
|
+
if (Array.from(query).length > 128) throw new Error('Fuzzy query must contain at most 128 Unicode code points.');
|
|
328
|
+
if ((query.match(/[\p{L}\p{N}_]+/gu) || []).length > 16) throw new Error('Fuzzy query must contain at most 16 word terms (Unicode letters, numbers, or underscore).');
|
|
329
|
+
}
|
|
330
|
+
return query;
|
|
331
|
+
}
|
|
332
|
+
// Rendered text is transient request data: no catalog, storage or tool access.
|
|
333
|
+
// Full-document ranges reuse the search algorithms and one timed VM batch.
|
|
334
|
+
export function highlightText(input) {
|
|
335
|
+
if (!input || typeof input !== 'object' || Array.isArray(input)) throw new Error('Expected a highlight request');
|
|
336
|
+
const options = matchOptions(input);
|
|
337
|
+
const query = matchQuery(input.query, options.fuzzy);
|
|
338
|
+
if (!Array.isArray(input.texts) || input.texts.length > MAX_HIGHLIGHT_TEXTS) throw new Error(`texts must be an array of at most ${MAX_HIGHLIGHT_TEXTS} text blocks`);
|
|
339
|
+
let size = 0;
|
|
340
|
+
const documents = Array.from(input.texts, (text, index) => {
|
|
341
|
+
if (typeof text !== 'string') throw new Error('Every text block must be a string');
|
|
342
|
+
size += text.length;
|
|
343
|
+
if (size > MAX_HIGHLIGHT_TEXT) throw new Error(`texts exceed ${MAX_HIGHLIGHT_TEXT} UTF-16 code units`);
|
|
344
|
+
return {text, index};
|
|
345
|
+
});
|
|
346
|
+
return matchDocuments(documents, {query, ...options}, {maxTotalRanges: MAX_HIGHLIGHT_TOTAL_RANGES});
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
export async function search(services, input, signal = new AbortController().signal) {
|
|
350
|
+
if (!input || typeof input !== 'object' || Array.isArray(input)) throw new Error('Expected a search request');
|
|
351
|
+
signal.throwIfAborted();
|
|
352
|
+
const action = choice(input.action, 'search', ['sessions', 'search', 'groups'], 'action');
|
|
353
|
+
const includeSubagents = flag(input.includeSubagents, 'includeSubagents');
|
|
354
|
+
const includeArchived = flag(input.includeArchived, 'includeArchived');
|
|
355
|
+
const {matchCase, wholeWord, useRegex, fuzzy} = matchOptions(input);
|
|
356
|
+
const content = choice(input.content, 'final', ['final', 'all'], 'content mode');
|
|
357
|
+
const order = choice(input.order, 'newest', ['newest', 'oldest'], 'result order');
|
|
358
|
+
const options = {includeSubagents, includeArchived, content, order, matchCase, wholeWord, useRegex, fuzzy};
|
|
359
|
+
const query = action !== 'sessions' ? matchQuery(input.query, fuzzy) : undefined;
|
|
360
|
+
const sessionIds = selection(input, 'sessionId', 'sessionIds', 1000);
|
|
361
|
+
const workspaceIds = selection(input, 'workspaceId', 'workspaceIds', 200);
|
|
362
|
+
const after = timestamp(input.after, 'after'), before = timestamp(input.before, 'before');
|
|
363
|
+
if (after !== undefined && before !== undefined && after >= before) throw new Error('after must be less than before');
|
|
364
|
+
const bounded = after !== undefined || before !== undefined;
|
|
365
|
+
const key = digest(['v1.8', action, query, sessionIds, workspaceIds, after, before, options]);
|
|
366
|
+
let cursor;
|
|
367
|
+
if (input.cursor !== undefined) {
|
|
368
|
+
try {
|
|
369
|
+
cursor = JSON.parse(Buffer.from(string(input.cursor, 'cursor', 16384), 'base64url').toString());
|
|
370
|
+
if (cursor.key !== key || !Number.isSafeInteger(cursor.offset) || cursor.offset < 0 || typeof cursor.version !== 'string') throw new Error();
|
|
371
|
+
} catch {throw new Error('Invalid search cursor. Search again.');}
|
|
372
|
+
}
|
|
373
|
+
const spec = {query, matchCase, wholeWord, useRegex, fuzzy};
|
|
374
|
+
// Validate even with an empty/excluded corpus, before any service reads.
|
|
375
|
+
if (action !== 'sessions') matchDocuments([], spec);
|
|
376
|
+
const {items: rows, workspaces} = await catalog(services, options, signal);
|
|
377
|
+
const workspaceSelection = new Set(workspaceIds), sessionSelection = new Set(sessionIds);
|
|
378
|
+
const byWorkspace = new Map(workspaces.map(item => [item.workspaceId, item]));
|
|
379
|
+
const bySession = new Map(rows.map(row => [row.sessionId, row]));
|
|
380
|
+
for (const id of workspaceIds) {
|
|
381
|
+
if (!byWorkspace.has(id)) throw new Error('Workspace is unavailable. Refresh the workspace list and search again.');
|
|
382
|
+
}
|
|
383
|
+
for (const id of sessionIds) {
|
|
384
|
+
const selected = bySession.get(id);
|
|
385
|
+
if (!selected) throw new Error('Session is unavailable or excluded. Refresh the list or enable its archive/subagent scope.');
|
|
386
|
+
if (workspaceIds.length && !workspaceSelection.has(selected.workspaceId)) throw new Error('Session does not belong to the selected workspace scope. Choose a session in a selected workspace or clear the session scope.');
|
|
387
|
+
}
|
|
388
|
+
const eligible = rows.filter(row => (!sessionIds.length || sessionSelection.has(row.sessionId)) && (!workspaceIds.length || workspaceSelection.has(row.workspaceId)));
|
|
389
|
+
const workspaceId = workspaceIds.length === 1 ? workspaceIds[0] : undefined;
|
|
390
|
+
const workspace = byWorkspace.get(workspaceId);
|
|
391
|
+
const scope = {scope: sessionIds.length === 1 ? sessionIds[0] : 'all', workspaceId: workspaceId ?? null,
|
|
392
|
+
workspaceTitle: workspace?.title || '', workspacePath: workspace?.path || '', workspaces,
|
|
393
|
+
sessionIds, workspaceIds, after: after ?? null, before: before ?? null};
|
|
394
|
+
if (action === 'sessions') return {...scope, ...options, items: eligible};
|
|
395
|
+
const items = [], warnings = [];
|
|
396
|
+
let hasExactMatches = false;
|
|
397
|
+
for (const row of eligible) {
|
|
398
|
+
signal.throwIfAborted();
|
|
399
|
+
try {
|
|
400
|
+
const observation = await services.sessionQuery.observeSession(row.sessionId, {signal, projectionMode: 'none'});
|
|
401
|
+
try {
|
|
402
|
+
const project = content === 'final' ? finalDocuments : processDocuments;
|
|
403
|
+
const projected = project(observation.events, row.sessionId);
|
|
404
|
+
// Project full turns first: cutting events can erase a turn's completion
|
|
405
|
+
// or wrongly promote an earlier assistant message into its final reply.
|
|
406
|
+
// Filter before BOTH fuzzy exact-presence scans and hit aggregation.
|
|
407
|
+
const documents = bounded ? projected.filter(doc => Number.isSafeInteger(doc.time) && Math.abs(doc.time) <= MAX_DATE_MS &&
|
|
408
|
+
(after === undefined || doc.time >= after) && (before === undefined || doc.time < before)) : projected;
|
|
409
|
+
const matched = matchDocuments(documents, spec);
|
|
410
|
+
const hits = fuzzy === 'off' ? matched : matched.hits;
|
|
411
|
+
if (fuzzy !== 'off' && matched.hasExactMatches) hasExactMatches = true;
|
|
412
|
+
for (const hit of hits) items.push({...row, ...hit});
|
|
413
|
+
} finally {observation[Symbol.dispose]();}
|
|
414
|
+
signal.throwIfAborted();
|
|
415
|
+
} catch (error) {
|
|
416
|
+
signal.throwIfAborted();
|
|
417
|
+
// A pathological expression must stop ALL scopes, never silently hide
|
|
418
|
+
// the affected session behind an ordinary read-failure warning.
|
|
419
|
+
if (error instanceof SearchMatchError || sessionIds.length) throw error;
|
|
420
|
+
warnings.push({sessionId: row.sessionId, error: error instanceof Error ? error.message : String(error)});
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
// Search retains every matching reply/event. Groups aggregate this complete
|
|
424
|
+
// set BEFORE presentation pagination, never counts from a page of hits.
|
|
425
|
+
items.sort((a, b) => (order === 'newest' ? b.time - a.time : a.time - b.time) || a.sessionId.localeCompare(b.sessionId) || (order === 'newest' ? b.seq - a.seq : a.seq - b.seq));
|
|
426
|
+
// Bind group cursors to the full hits too: changing a non-extremal matching
|
|
427
|
+
// reply must invalidate a page even when its group's count/time is unchanged.
|
|
428
|
+
const exactMetadata = fuzzy === 'off' ? {} : {hasExactMatches};
|
|
429
|
+
const version = digest(fuzzy === 'off' ? [items, warnings] : [items, warnings, exactMetadata]);
|
|
430
|
+
if (cursor && cursor.version !== version) throw new Error('History changed. Search again to refresh results.');
|
|
431
|
+
let results = items;
|
|
432
|
+
if (action === 'groups') {
|
|
433
|
+
const metadata = new Map(eligible.map(row => [row.sessionId, row]));
|
|
434
|
+
const groups = new Map();
|
|
435
|
+
for (const hit of items) {
|
|
436
|
+
let group = groups.get(hit.sessionId);
|
|
437
|
+
if (!group) {
|
|
438
|
+
// First hit in chronological result order supplies the requested
|
|
439
|
+
// newest/oldest matching time, NOT the catalog's latest activity.
|
|
440
|
+
group = {...metadata.get(hit.sessionId), count: 0, time: hit.time};
|
|
441
|
+
groups.set(hit.sessionId, group);
|
|
442
|
+
}
|
|
443
|
+
group.count++;
|
|
444
|
+
}
|
|
445
|
+
results = [...groups.values()];
|
|
446
|
+
}
|
|
447
|
+
const offset = cursor?.offset ?? 0;
|
|
448
|
+
if (offset > results.length) throw new Error('Invalid search cursor. Search again.');
|
|
449
|
+
const end = offset + LIMIT;
|
|
450
|
+
return {...scope, query, ...options, ...exactMetadata, items: results.slice(offset, end), total: results.length, scanned: eligible.length,
|
|
451
|
+
...(action === 'groups' ? {totalMatches: items.length} : {}),
|
|
452
|
+
...(warnings.length ? {warnings} : {}),
|
|
453
|
+
...(end < results.length ? {nextCursor: Buffer.from(JSON.stringify({key, version, offset: end})).toString('base64url')} : {})};
|
|
454
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
export const LIMIT = 40;
|
|
2
|
+
// Read one public Workspace baseline and close the follower immediately.
|
|
3
|
+
export async function workspaceSnapshot(controller, signal) {
|
|
4
|
+
const stream = controller.follow(signal);
|
|
5
|
+
try {
|
|
6
|
+
const frame = await stream.next();
|
|
7
|
+
if (frame.done || frame.value.type !== 'baseline') throw new Error('Workspace catalog unavailable');
|
|
8
|
+
return frame.value.value;
|
|
9
|
+
} finally {await stream.return();}
|
|
10
|
+
}
|
|
11
|
+
export const UNGROUPED_WORKSPACE_ID = '__ungrouped__';
|
|
12
|
+
// Compare exact cwd roots only; a descendant directory is not evidence of
|
|
13
|
+
// registry membership. Windows roots are case-insensitive, POSIX roots are not.
|
|
14
|
+
function pathKey(value) {
|
|
15
|
+
if (typeof value !== 'string' || !value) return '';
|
|
16
|
+
const path = value.replace(/\\/g, '/').replace(/\/+$/u, '') || '/';
|
|
17
|
+
return /^[a-z]:(?:\/|$)/iu.test(path) || path.startsWith('//') ? path.toLowerCase() : path;
|
|
18
|
+
}
|
|
19
|
+
export function workspaceCatalog(snapshot) {
|
|
20
|
+
return [...snapshot.items.map(({workspaceId, title, path, createdAt, updatedAt}) => ({workspaceId, title, path, createdAt, updatedAt, sessionCount: 0})),
|
|
21
|
+
{workspaceId: UNGROUPED_WORKSPACE_ID, title: 'Ungrouped sessions', path: '', sessionCount: 0, ungrouped: true}];
|
|
22
|
+
}
|
|
23
|
+
function workspaceAssignments(snapshot, records) {
|
|
24
|
+
const membership = new Map(), roots = new Map(), resolved = new Map();
|
|
25
|
+
const unique = (map, key, workspaceId) => {
|
|
26
|
+
if (!map.has(key)) map.set(key, workspaceId);
|
|
27
|
+
else if (map.get(key) !== workspaceId) map.set(key, UNGROUPED_WORKSPACE_ID);
|
|
28
|
+
};
|
|
29
|
+
for (const workspace of snapshot.items) {
|
|
30
|
+
for (const id of workspace.sessionIds) unique(membership, id, workspace.workspaceId);
|
|
31
|
+
const root = pathKey(workspace.path);
|
|
32
|
+
if (root) unique(roots, root, workspace.workspaceId);
|
|
33
|
+
}
|
|
34
|
+
return sessionId => {
|
|
35
|
+
let current = sessionId, workspaceId;
|
|
36
|
+
const chain = new Set();
|
|
37
|
+
while (current) {
|
|
38
|
+
if (membership.has(current)) {workspaceId = membership.get(current); break;}
|
|
39
|
+
if (resolved.has(current)) {workspaceId = resolved.get(current); break;}
|
|
40
|
+
if (chain.has(current)) break;
|
|
41
|
+
chain.add(current);
|
|
42
|
+
const row = records.get(current);
|
|
43
|
+
if (!row) break;
|
|
44
|
+
// An explicit parent, even archived/blank or missing from the sidebar,
|
|
45
|
+
// takes precedence over the child's cwd. Follow nested parents safely.
|
|
46
|
+
if (row.origin === 'subagent' && row.parentSessionId) {current = row.parentSessionId; continue;}
|
|
47
|
+
workspaceId = roots.get(pathKey(row.cwd));
|
|
48
|
+
break;
|
|
49
|
+
}
|
|
50
|
+
workspaceId ??= UNGROUPED_WORKSPACE_ID;
|
|
51
|
+
for (const id of chain) resolved.set(id, workspaceId);
|
|
52
|
+
return workspaceId;
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
export async function catalog(services, input, signal) {
|
|
56
|
+
const [list, snapshot] = await Promise.all([
|
|
57
|
+
services.sessionController.list({}, signal), workspaceSnapshot(services.workspaceController, signal),
|
|
58
|
+
]);
|
|
59
|
+
signal.throwIfAborted();
|
|
60
|
+
const archived = new Set(snapshot.archivedSessionIds);
|
|
61
|
+
// Keep excluded parents as assignment evidence, never as eligible results.
|
|
62
|
+
const records = new Map();
|
|
63
|
+
for (const row of list.items) if (!records.has(row.sessionId)) records.set(row.sessionId, row);
|
|
64
|
+
const rows = [...records.values()].filter(row => !row.blank && (input.includeSubagents || row.origin !== 'subagent') && (input.includeArchived || !archived.has(row.sessionId)));
|
|
65
|
+
// Cold subagents need not have a cwd, so the ordinary sidebar catalog may
|
|
66
|
+
// omit them. Supplement only explicit subagent origins when opted in.
|
|
67
|
+
if (input.includeSubagents) {
|
|
68
|
+
for (const {header} of await services.sessionQuery.listSessions(signal)) {
|
|
69
|
+
if (records.has(header.id)) continue;
|
|
70
|
+
const row = {sessionId: header.id, updatedAt: header.createdAt, origin: header.origin, parentSessionId: header.parentSession, cwd: header.cwd};
|
|
71
|
+
records.set(header.id, row);
|
|
72
|
+
if (header.origin === 'subagent' && (input.includeArchived || !archived.has(header.id))) rows.push(row);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
signal.throwIfAborted();
|
|
76
|
+
const workspaces = workspaceCatalog(snapshot);
|
|
77
|
+
const byWorkspace = new Map(workspaces.map(workspace => [workspace.workspaceId, workspace]));
|
|
78
|
+
const assignment = workspaceAssignments(snapshot, records);
|
|
79
|
+
const titles = new Map();
|
|
80
|
+
const missing = rows.filter(row => row.projections?.values?.title === undefined).map(row => row.sessionId);
|
|
81
|
+
if (missing.length) {
|
|
82
|
+
for (const result of await services.sessionQuery.readTitleSnapshots(missing, signal)) {
|
|
83
|
+
if (result.status === 'fulfilled') titles.set(result.sessionId, result.value.title?.title);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
rows.sort((a, b) => b.updatedAt - a.updatedAt || (a.sessionId < b.sessionId ? -1 : a.sessionId > b.sessionId ? 1 : 0));
|
|
87
|
+
const items = rows.map(row => {
|
|
88
|
+
const workspace = byWorkspace.get(assignment(row.sessionId));
|
|
89
|
+
workspace.sessionCount++;
|
|
90
|
+
return {sessionId: row.sessionId, title: (row.projections?.values?.title ?? titles.get(row.sessionId))?.trim() || '', updatedAt: row.updatedAt,
|
|
91
|
+
cwd: row.cwd || '', archived: archived.has(row.sessionId), subagent: row.origin === 'subagent',
|
|
92
|
+
workspaceId: workspace.workspaceId, workspaceTitle: workspace.title, workspacePath: workspace.path,
|
|
93
|
+
...(row.parentSessionId ? {parentSession: row.parentSessionId} : {})};
|
|
94
|
+
});
|
|
95
|
+
return {items, workspaces};
|
|
96
|
+
}
|
|
97
|
+
// A final reply is the last successful text-only assistant response in a
|
|
98
|
+
// completed turn, not commentary before tools or an abandoned partial attempt.
|
|
99
|
+
export function finalDocuments(events, sessionId) {
|
|
100
|
+
const documents = [];
|
|
101
|
+
let candidate;
|
|
102
|
+
let turn;
|
|
103
|
+
for (const event of events) {
|
|
104
|
+
if (event.type === 'turn/start') {turn = event.data.turn; candidate = undefined;}
|
|
105
|
+
if (event.type === 'assistant/message' && event.data.turn === turn) candidate = event;
|
|
106
|
+
if (event.type !== 'turn/end' || event.data.turn !== turn) continue;
|
|
107
|
+
if (event.data.reason.kind === 'completed' && candidate && !candidate.data.interrupted) {
|
|
108
|
+
const content = candidate.data.message.content;
|
|
109
|
+
if (!content.some(block => block.type === 'tool-call')) {
|
|
110
|
+
const text = content.filter(block => block.type === 'text').map(block => block.text).join('\n').trim();
|
|
111
|
+
if (text) documents.push({sessionId, seq: candidate.seq, time: candidate.time, type: candidate.type, text});
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
candidate = undefined; turn = undefined;
|
|
115
|
+
}
|
|
116
|
+
return documents;
|
|
117
|
+
}
|
|
118
|
+
export function processDocuments(events, sessionId) {
|
|
119
|
+
const blockText = blocks => (blocks || []).flatMap(block => {
|
|
120
|
+
if (block.type === 'text' || block.type === 'reasoning') return [block.text];
|
|
121
|
+
if (block.type === 'tool-call') return [block.name, block.arguments];
|
|
122
|
+
return [];
|
|
123
|
+
}).join('\n');
|
|
124
|
+
return events.flatMap(event => {
|
|
125
|
+
let text = '';
|
|
126
|
+
if (event.type === 'user/message') text = blockText(event.data.content);
|
|
127
|
+
else if (['assistant/message', 'tool/result', 'developer/message', 'system/message'].includes(event.type)) text = blockText(event.data.message.content);
|
|
128
|
+
else if (event.type === 'tool/call') text = `${event.data.name}\n${event.data.arguments}`;
|
|
129
|
+
else if (event.type === 'assistant/attempt') text = (event.data.stream || []).flatMap(record => {
|
|
130
|
+
if (record.type === 'text-chunks' || record.type === 'reasoning-chunks') return record.texts;
|
|
131
|
+
if (record.type === 'chunk' && ['text-delta', 'reasoning-delta'].includes(record.chunk.type)) return [record.chunk.text];
|
|
132
|
+
return [];
|
|
133
|
+
}).join('');
|
|
134
|
+
return text.trim() ? [{sessionId, seq: event.seq, time: event.time, type: event.type, text}] : [];
|
|
135
|
+
});
|
|
136
|
+
}
|
package/settings.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// Standard Schema keeps this plugin dependency-free while validating Loader config.
|
|
2
|
+
const schema = {type: 'object', properties: {searchMode: {type: 'string', enum: ['live', 'submit'], default: 'live'}}, additionalProperties: false};
|
|
3
|
+
export function validateSettings(input) {
|
|
4
|
+
const value = input === undefined ? {} : input;
|
|
5
|
+
if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).some(key => key !== 'searchMode')) throw new Error('Expected settings with only searchMode');
|
|
6
|
+
const searchMode = value.searchMode === undefined ? 'live' : value.searchMode;
|
|
7
|
+
if (!['live', 'submit'].includes(searchMode)) throw new Error('searchMode must be live or submit');
|
|
8
|
+
return {searchMode};
|
|
9
|
+
}
|
|
10
|
+
export const Config = {
|
|
11
|
+
'~standard': {version: 1, vendor: 'dsh-session-search', validate(input) {
|
|
12
|
+
try {return {value: validateSettings(input)};} catch (error) {return {issues: [{message: error.message}]};}
|
|
13
|
+
}},
|
|
14
|
+
'~standard-json-schema': {version: 1, vendor: 'dsh-session-search', input: () => schema, output: () => schema}
|
|
15
|
+
};
|
|
16
|
+
export function createSettingsOperation(ctx, config) {
|
|
17
|
+
let entryId;
|
|
18
|
+
const entry = () => {
|
|
19
|
+
const entries = ctx.configEditor.entries();
|
|
20
|
+
entryId ??= entries.find(item => item.fiber?.uid === ctx.fiber.uid)?.options.id;
|
|
21
|
+
const found = entries.find(item => item.options.id === entryId && item.options.name === '@lizimin/dsh-session-search');
|
|
22
|
+
if (!found) throw new Error('Session Search configuration is unavailable');
|
|
23
|
+
return found;
|
|
24
|
+
};
|
|
25
|
+
return async function settings(input) {
|
|
26
|
+
if (input !== undefined) {
|
|
27
|
+
const next = validateSettings(input);
|
|
28
|
+
await ctx.configEditor.edit(entry(), current => ({...current, ...next}));
|
|
29
|
+
}
|
|
30
|
+
return validateSettings(entry().fiber?.config ?? config);
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
export async function readSettingsBody(req) {
|
|
34
|
+
let size = 0;
|
|
35
|
+
const chunks = [];
|
|
36
|
+
for await (const chunk of req) {
|
|
37
|
+
size += Buffer.byteLength(chunk);
|
|
38
|
+
if (size > 1024) throw new Error('Settings body exceeds 1024 bytes');
|
|
39
|
+
chunks.push(Buffer.from(chunk));
|
|
40
|
+
}
|
|
41
|
+
try {return validateSettings(JSON.parse(Buffer.concat(chunks).toString('utf8')));} catch (error) {throw new Error(`Invalid settings: ${error.message}`);}
|
|
42
|
+
}
|