@semics-tech/mongolite 1.1.0 → 1.3.0

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.
Files changed (54) hide show
  1. package/README.md +54 -3
  2. package/dist/adapters/node-sqlite.d.ts +4 -0
  3. package/dist/adapters/node-sqlite.js +80 -35
  4. package/dist/adapters/node-sqlite.js.map +1 -1
  5. package/dist/bin/mongolite-debug.d.ts +6 -1
  6. package/dist/bin/mongolite-debug.js +6 -113
  7. package/dist/bin/mongolite-debug.js.map +1 -1
  8. package/dist/bin/mongolite.d.ts +13 -0
  9. package/dist/bin/mongolite.js +172 -0
  10. package/dist/bin/mongolite.js.map +1 -0
  11. package/dist/cjs/adapters/node-sqlite.js +84 -35
  12. package/dist/cjs/bin/mongolite-debug.js +6 -149
  13. package/dist/cjs/bin/mongolite.js +207 -0
  14. package/dist/cjs/cli/discover.js +156 -0
  15. package/dist/cjs/cli/explorer.js +929 -0
  16. package/dist/cjs/cli/filter-builder.js +276 -0
  17. package/dist/cjs/cli/format.js +161 -0
  18. package/dist/cjs/cli/schema.js +211 -0
  19. package/dist/cjs/cli/ui.js +431 -0
  20. package/dist/cjs/collection.js +53 -14
  21. package/dist/cjs/cursors/findCursor.js +108 -19
  22. package/dist/cjs/db.js +87 -40
  23. package/dist/cjs/utils/connection-registry.js +122 -0
  24. package/dist/cli/discover.d.ts +40 -0
  25. package/dist/cli/discover.js +146 -0
  26. package/dist/cli/discover.js.map +1 -0
  27. package/dist/cli/explorer.d.ts +59 -0
  28. package/dist/cli/explorer.js +923 -0
  29. package/dist/cli/explorer.js.map +1 -0
  30. package/dist/cli/filter-builder.d.ts +52 -0
  31. package/dist/cli/filter-builder.js +268 -0
  32. package/dist/cli/filter-builder.js.map +1 -0
  33. package/dist/cli/format.d.ts +29 -0
  34. package/dist/cli/format.js +153 -0
  35. package/dist/cli/format.js.map +1 -0
  36. package/dist/cli/schema.d.ts +58 -0
  37. package/dist/cli/schema.js +205 -0
  38. package/dist/cli/schema.js.map +1 -0
  39. package/dist/cli/ui.d.ts +71 -0
  40. package/dist/cli/ui.js +379 -0
  41. package/dist/cli/ui.js.map +1 -0
  42. package/dist/collection.d.ts +25 -0
  43. package/dist/collection.js +53 -14
  44. package/dist/collection.js.map +1 -1
  45. package/dist/cursors/findCursor.d.ts +70 -0
  46. package/dist/cursors/findCursor.js +108 -19
  47. package/dist/cursors/findCursor.js.map +1 -1
  48. package/dist/db.d.ts +23 -0
  49. package/dist/db.js +85 -39
  50. package/dist/db.js.map +1 -1
  51. package/dist/utils/connection-registry.d.ts +74 -0
  52. package/dist/utils/connection-registry.js +117 -0
  53. package/dist/utils/connection-registry.js.map +1 -0
  54. package/package.json +2 -1
package/dist/cli/ui.js ADDED
@@ -0,0 +1,379 @@
1
+ /**
2
+ * Small, dependency-free terminal UI helpers used by the guided MongoLite CLI.
3
+ *
4
+ * Everything degrades gracefully:
5
+ * - When stdin/stdout is a TTY the prompts are interactive (arrow keys, filtering).
6
+ * - When it is not (pipes, CI, dumb terminals) the same prompts fall back to a
7
+ * numbered list read line-by-line, so the CLI stays scriptable.
8
+ */
9
+ import * as readline from 'node:readline';
10
+ const NO_COLOR = process.env.NO_COLOR !== undefined || process.env.TERM === 'dumb';
11
+ export const isInteractive = () => Boolean(process.stdin.isTTY && process.stdout.isTTY && !process.env.MONGOLITE_NON_INTERACTIVE);
12
+ const wrap = (open, close) => (text) => NO_COLOR || !process.stdout.isTTY ? text : `\u001b[${open}m${text}\u001b[${close}m`;
13
+ export const style = {
14
+ bold: wrap('1', '22'),
15
+ dim: wrap('2', '22'),
16
+ italic: wrap('3', '23'),
17
+ underline: wrap('4', '24'),
18
+ red: wrap('31', '39'),
19
+ green: wrap('32', '39'),
20
+ yellow: wrap('33', '39'),
21
+ blue: wrap('34', '39'),
22
+ magenta: wrap('35', '39'),
23
+ cyan: wrap('36', '39'),
24
+ grey: wrap('90', '39'),
25
+ };
26
+ /** Visible width of a string, ignoring ANSI escape sequences. */
27
+ export function displayWidth(text) {
28
+ return text.replace(/\u001b\[[0-9;]*m/g, '').length;
29
+ }
30
+ /** Truncate to `max` visible characters, appending an ellipsis when cut. */
31
+ export function truncate(text, max) {
32
+ if (max <= 0)
33
+ return '';
34
+ if (text.length <= max)
35
+ return text;
36
+ if (max <= 1)
37
+ return text.slice(0, max);
38
+ return `${text.slice(0, max - 1)}…`;
39
+ }
40
+ export function terminalWidth() {
41
+ return Math.max(40, process.stdout.columns || 100);
42
+ }
43
+ /** Thrown when the user aborts a prompt with Esc or Ctrl+C. */
44
+ export class PromptCancelledError extends Error {
45
+ constructor() {
46
+ super('Prompt cancelled');
47
+ this.name = 'PromptCancelledError';
48
+ }
49
+ }
50
+ function selectableIndexes(choices) {
51
+ return choices.map((c, i) => (c.separator ? -1 : i)).filter((i) => i >= 0);
52
+ }
53
+ /**
54
+ * Ask the user to pick one of `choices`.
55
+ * Interactive terminals get an arrow-key menu with type-to-filter; everything
56
+ * else gets a numbered list.
57
+ */
58
+ export async function select(options) {
59
+ if (options.choices.length === 0) {
60
+ throw new Error(`Nothing to choose from for: ${options.message}`);
61
+ }
62
+ const selectable = selectableIndexes(options.choices);
63
+ if (selectable.length === 1 && options.choices.length === 1) {
64
+ // Nothing to decide - tell the user what was picked for them and move on.
65
+ const only = options.choices[selectable[0]];
66
+ process.stdout.write(`${style.green('?')} ${style.bold(options.message)} ${style.cyan(only.label)} ${style.grey('(only option)')}\n`);
67
+ return only.value;
68
+ }
69
+ return isInteractive() ? interactiveSelect(options) : fallbackSelect(options);
70
+ }
71
+ async function interactiveSelect(options) {
72
+ const { message, choices } = options;
73
+ const pageSize = Math.min(options.pageSize ?? 12, Math.max(3, (process.stdout.rows || 24) - 6));
74
+ let filter = '';
75
+ let cursor = 0;
76
+ let renderedLines = 0;
77
+ const visible = () => {
78
+ const lowered = filter.toLowerCase();
79
+ return choices
80
+ .map((choice, index) => ({ choice, index }))
81
+ .filter(({ choice }) => {
82
+ if (!filter)
83
+ return true;
84
+ if (choice.separator)
85
+ return false;
86
+ return `${choice.label} ${choice.hint ?? ''}`.toLowerCase().includes(lowered);
87
+ });
88
+ };
89
+ const selectablePositions = (list) => list.map((entry, pos) => (entry.choice.separator ? -1 : pos)).filter((pos) => pos >= 0);
90
+ const initial = options.initialIndex ?? 0;
91
+ {
92
+ const list = visible();
93
+ const positions = selectablePositions(list);
94
+ const wanted = list.findIndex((entry) => entry.index === initial);
95
+ cursor = positions.includes(wanted) ? wanted : (positions[0] ?? 0);
96
+ }
97
+ const clear = () => {
98
+ if (renderedLines > 0) {
99
+ process.stdout.write(`\u001b[${renderedLines}A`);
100
+ process.stdout.write('\u001b[0J');
101
+ }
102
+ renderedLines = 0;
103
+ };
104
+ const render = () => {
105
+ clear();
106
+ const width = terminalWidth();
107
+ const list = visible();
108
+ const positions = selectablePositions(list);
109
+ if (positions.length && !positions.includes(cursor)) {
110
+ cursor = positions[0];
111
+ }
112
+ const lines = [];
113
+ const filterSuffix = filter ? ` ${style.yellow(`/${filter}`)}` : '';
114
+ lines.push(`${style.green('?')} ${style.bold(message)}${filterSuffix}`);
115
+ lines.push(style.grey(options.hint ?? ' ↑/↓ move · type to filter · enter to select · esc to go back'));
116
+ // Scroll window so the cursor stays visible.
117
+ let start = 0;
118
+ if (list.length > pageSize) {
119
+ start = Math.min(Math.max(0, cursor - Math.floor(pageSize / 2)), list.length - pageSize);
120
+ }
121
+ const window = list.slice(start, start + pageSize);
122
+ if (window.length === 0) {
123
+ lines.push(style.grey(' no matches'));
124
+ }
125
+ window.forEach((entry, offset) => {
126
+ const pos = start + offset;
127
+ const { choice } = entry;
128
+ if (choice.separator) {
129
+ lines.push(style.grey(` ${choice.label}`));
130
+ return;
131
+ }
132
+ const active = pos === cursor;
133
+ const pointer = active ? style.cyan('❯') : ' ';
134
+ const label = active ? style.cyan(choice.label) : choice.label;
135
+ const hint = choice.hint ? ` ${style.grey(choice.hint)}` : '';
136
+ const line = `${pointer} ${label}${hint}`;
137
+ lines.push(displayWidth(line) > width ? truncate(line, width) : line);
138
+ });
139
+ if (list.length > pageSize) {
140
+ lines.push(style.grey(` … ${start + window.length}/${list.length}`));
141
+ }
142
+ process.stdout.write(`${lines.join('\n')}\n`);
143
+ renderedLines = lines.length;
144
+ };
145
+ return new Promise((resolve, reject) => {
146
+ readline.emitKeypressEvents(process.stdin);
147
+ const wasRaw = process.stdin.isRaw;
148
+ process.stdin.setRawMode(true);
149
+ process.stdin.resume();
150
+ const finish = (fn) => {
151
+ process.stdin.removeListener('keypress', onKeypress);
152
+ process.stdin.setRawMode(Boolean(wasRaw));
153
+ process.stdin.pause();
154
+ fn();
155
+ };
156
+ const onKeypress = (str, key) => {
157
+ const list = visible();
158
+ const positions = selectablePositions(list);
159
+ if (key.ctrl && key.name === 'c') {
160
+ clear();
161
+ finish(() => {
162
+ process.stdout.write(style.grey('Cancelled.\n'));
163
+ process.exit(0);
164
+ });
165
+ return;
166
+ }
167
+ switch (key.name) {
168
+ case 'escape':
169
+ clear();
170
+ finish(() => reject(new PromptCancelledError()));
171
+ return;
172
+ case 'up': {
173
+ const at = positions.indexOf(cursor);
174
+ cursor = positions[(at - 1 + positions.length) % positions.length] ?? cursor;
175
+ render();
176
+ return;
177
+ }
178
+ case 'down': {
179
+ const at = positions.indexOf(cursor);
180
+ cursor = positions[(at + 1) % positions.length] ?? cursor;
181
+ render();
182
+ return;
183
+ }
184
+ case 'pageup':
185
+ cursor = positions[0] ?? cursor;
186
+ render();
187
+ return;
188
+ case 'pagedown':
189
+ cursor = positions[positions.length - 1] ?? cursor;
190
+ render();
191
+ return;
192
+ case 'return':
193
+ case 'enter': {
194
+ const chosen = list[cursor];
195
+ if (!chosen || chosen.choice.separator)
196
+ return;
197
+ clear();
198
+ process.stdout.write(`${style.green('?')} ${style.bold(message)} ${style.cyan(chosen.choice.label)}\n`);
199
+ finish(() => resolve(chosen.choice.value));
200
+ return;
201
+ }
202
+ case 'backspace':
203
+ filter = filter.slice(0, -1);
204
+ render();
205
+ return;
206
+ default:
207
+ break;
208
+ }
209
+ if (str && !key.ctrl && !key.meta && str >= ' ' && str <= '~') {
210
+ filter += str;
211
+ render();
212
+ }
213
+ };
214
+ process.stdin.on('keypress', onKeypress);
215
+ render();
216
+ });
217
+ }
218
+ async function fallbackSelect(options) {
219
+ const { message, choices } = options;
220
+ const numbered = choices
221
+ .map((choice, index) => ({ choice, index }))
222
+ .filter((e) => !e.choice.separator);
223
+ process.stdout.write(`\n${style.bold(message)}\n`);
224
+ numbered.forEach((entry, position) => {
225
+ const hint = entry.choice.hint ? ` ${style.grey(entry.choice.hint)}` : '';
226
+ process.stdout.write(` ${position + 1}) ${entry.choice.label}${hint}\n`);
227
+ });
228
+ for (;;) {
229
+ const answer = (await question(`Choose 1-${numbered.length}: `)).trim();
230
+ if (answer === '')
231
+ continue;
232
+ const position = Number.parseInt(answer, 10);
233
+ if (Number.isInteger(position) && position >= 1 && position <= numbered.length) {
234
+ return numbered[position - 1].choice.value;
235
+ }
236
+ // Also accept an exact (case-insensitive) label so scripted input stays readable.
237
+ const byLabel = numbered.find((entry) => entry.choice.label.toLowerCase() === answer.toLowerCase());
238
+ if (byLabel)
239
+ return byLabel.choice.value;
240
+ process.stdout.write(style.red(' Not a valid choice, try again.\n'));
241
+ }
242
+ }
243
+ /**
244
+ * A single readline interface is reused for line input when stdin is not a
245
+ * TTY. Creating one per prompt would work for a human typing, but a *piped*
246
+ * script has all its answers buffered at once: closing the interface after the
247
+ * first question discards every remaining line. Interactive sessions still get
248
+ * a throwaway interface per prompt so they can coexist with the raw-mode
249
+ * keypress handling in `select`.
250
+ */
251
+ let sharedInterface = null;
252
+ let stdinEnded = false;
253
+ /** Lines that arrived before anything asked for them. */
254
+ const bufferedLines = [];
255
+ /** Callbacks waiting for the next line; `null` means stdin ended first. */
256
+ const lineWaiters = [];
257
+ function getSharedInterface() {
258
+ if (!sharedInterface) {
259
+ sharedInterface = readline.createInterface({
260
+ input: process.stdin,
261
+ output: process.stdout,
262
+ });
263
+ // Queue every line as it arrives. Piped input delivers all of its lines
264
+ // immediately, long before the later prompts ask for them.
265
+ sharedInterface.on('line', (line) => {
266
+ const waiter = lineWaiters.shift();
267
+ if (waiter)
268
+ waiter(line);
269
+ else
270
+ bufferedLines.push(line);
271
+ });
272
+ sharedInterface.on('close', () => {
273
+ stdinEnded = true;
274
+ while (lineWaiters.length > 0)
275
+ lineWaiters.shift()?.(null);
276
+ });
277
+ }
278
+ return sharedInterface;
279
+ }
280
+ /** Release the shared interface so the process can exit. */
281
+ export function closePrompts() {
282
+ sharedInterface?.close();
283
+ sharedInterface = null;
284
+ }
285
+ /** Read a single line from stdin. */
286
+ export function question(prompt) {
287
+ if (isInteractive()) {
288
+ return new Promise((resolve) => {
289
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
290
+ rl.question(prompt, (answer) => {
291
+ rl.close();
292
+ resolve(answer);
293
+ });
294
+ });
295
+ }
296
+ getSharedInterface();
297
+ process.stdout.write(prompt);
298
+ const buffered = bufferedLines.shift();
299
+ if (buffered !== undefined) {
300
+ process.stdout.write(`${buffered}\n`);
301
+ return Promise.resolve(buffered);
302
+ }
303
+ if (stdinEnded) {
304
+ // Input is exhausted - carrying on would spin forever re-asking.
305
+ process.stdout.write(`\n${style.grey('Input ended.')}\n`);
306
+ process.exit(0);
307
+ }
308
+ return new Promise((resolve) => {
309
+ lineWaiters.push((line) => {
310
+ if (line === null) {
311
+ process.stdout.write(`\n${style.grey('Input ended.')}\n`);
312
+ process.exit(0);
313
+ }
314
+ resolve(line);
315
+ });
316
+ });
317
+ }
318
+ /** Ask for free-text input, re-prompting until `validate` is happy. */
319
+ export async function text(options) {
320
+ const suffix = options.defaultValue ? style.grey(` (${options.defaultValue})`) : '';
321
+ if (options.hint)
322
+ process.stdout.write(`${style.grey(options.hint)}\n`);
323
+ for (;;) {
324
+ const raw = await question(`${style.green('?')} ${style.bold(options.message)}${suffix} `);
325
+ const value = raw.trim() === '' ? (options.defaultValue ?? '') : raw.trim();
326
+ if (value === '' && !options.allowEmpty && !options.defaultValue) {
327
+ process.stdout.write(style.red(' A value is required.\n'));
328
+ continue;
329
+ }
330
+ const error = options.validate?.(value);
331
+ if (error) {
332
+ process.stdout.write(`${style.red(` ${error}`)}\n`);
333
+ continue;
334
+ }
335
+ return value;
336
+ }
337
+ }
338
+ /** Ask for multi-line input; a blank line ends the entry. */
339
+ export async function multilineText(message) {
340
+ process.stdout.write(`${style.green('?')} ${style.bold(message)}\n`);
341
+ process.stdout.write(style.grey(' Finish with an empty line.\n'));
342
+ const lines = [];
343
+ for (;;) {
344
+ const line = await question(' ');
345
+ if (line.trim() === '')
346
+ break;
347
+ lines.push(line);
348
+ }
349
+ return lines.join('\n');
350
+ }
351
+ export async function confirm(message, defaultValue = false) {
352
+ const hint = defaultValue ? 'Y/n' : 'y/N';
353
+ const answer = (await question(`${style.green('?')} ${style.bold(message)} ${style.grey(`(${hint})`)} `))
354
+ .trim()
355
+ .toLowerCase();
356
+ if (answer === '')
357
+ return defaultValue;
358
+ return answer === 'y' || answer === 'yes';
359
+ }
360
+ /** Wait for the user before scrolling more output past them. */
361
+ export async function pause(message = 'Press enter to continue') {
362
+ await question(style.grey(`${message} `));
363
+ }
364
+ export function heading(text) {
365
+ process.stdout.write(`\n${style.bold(style.underline(text))}\n`);
366
+ }
367
+ export function info(text) {
368
+ process.stdout.write(`${text}\n`);
369
+ }
370
+ export function warn(text) {
371
+ process.stdout.write(`${style.yellow('!')} ${text}\n`);
372
+ }
373
+ export function error(text) {
374
+ process.stdout.write(`${style.red('✖')} ${text}\n`);
375
+ }
376
+ export function success(text) {
377
+ process.stdout.write(`${style.green('✔')} ${text}\n`);
378
+ }
379
+ //# sourceMappingURL=ui.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ui.js","sourceRoot":"","sources":["../../src/cli/ui.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,KAAK,QAAQ,MAAM,eAAe,CAAC;AAE1C,MAAM,QAAQ,GAAG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AC,GAAG,CAAC,IAAI,IAAI,IAAI,CAAC,CAAC;AACxD,CAAC"}
@@ -151,6 +151,31 @@ export declare class MongoLiteCollection<T extends DocumentWithId> {
151
151
  * @returns {Promise<number>} The count of matching documents.
152
152
  */
153
153
  countDocuments(filter?: Filter<T>): Promise<number>;
154
+ /**
155
+ * Finds rows whose stored `data` column is not valid JSON.
156
+ *
157
+ * Filtered queries deliberately skip these rows — see
158
+ * `FindCursor.buildGuardedWhereClause` — so that one corrupted document can't
159
+ * make the whole collection unqueryable. That keeps reads working, but it also
160
+ * means such rows quietly stop appearing in results. This is the way to find
161
+ * them so they can be repaired or deleted (`deleteOne({ _id })` works on them,
162
+ * since `_id` lookups don't go through json1 functions).
163
+ *
164
+ * Intended for integrity checks and ops tooling rather than hot paths: it scans
165
+ * the table and returns the raw column text, not parsed documents.
166
+ *
167
+ * @returns The `_id` and raw stored text of every invalid row.
168
+ */
169
+ findInvalidJson(): Promise<{
170
+ _id: string;
171
+ data: string;
172
+ }[]>;
173
+ /**
174
+ * Counts rows whose stored `data` column is not valid JSON.
175
+ * Cheap enough to run on a schedule as a health check.
176
+ * @see findInvalidJson
177
+ */
178
+ countInvalidJson(): Promise<number>;
154
179
  /**
155
180
  * Returns the number of documents in the collection.
156
181
  * This is an estimate and may not reflect the exact count in concurrent environments.
@@ -349,7 +349,7 @@ export class MongoLiteCollection {
349
349
  await this.ensureTable();
350
350
  // Find the document first (only one)
351
351
  const paramsForSelect = [];
352
- const whereClause = new FindCursor(this.db, this.name, filter)['buildWhereClause'](filter, paramsForSelect);
352
+ const whereClause = new FindCursor(this.db, this.name, filter)['buildGuardedWhereClause'](filter, paramsForSelect);
353
353
  const selectSql = `SELECT _id, data FROM "${this.name}" WHERE ${whereClause} LIMIT 1`;
354
354
  const rowToUpdate = await this.db.get(selectSql, paramsForSelect);
355
355
  if (!rowToUpdate && !options.upsert) {
@@ -478,7 +478,10 @@ export class MongoLiteCollection {
478
478
  const value = opArgs[path];
479
479
  const currentValue = this.getNestedValue(currentDoc, path);
480
480
  const arr = Array.isArray(currentValue) ? currentValue : [];
481
- const items = typeof value === 'object' && value !== null && '$each' in value && Array.isArray(value.$each)
481
+ const items = typeof value === 'object' &&
482
+ value !== null &&
483
+ '$each' in value &&
484
+ Array.isArray(value.$each)
482
485
  ? value.$each
483
486
  : [value];
484
487
  let changed = false;
@@ -614,7 +617,7 @@ export class MongoLiteCollection {
614
617
  async updateMany(filter, update) {
615
618
  await this.ensureTable();
616
619
  const paramsForSelect = [];
617
- const whereClause = new FindCursor(this.db, this.name, filter)['buildWhereClause'](filter, paramsForSelect);
620
+ const whereClause = new FindCursor(this.db, this.name, filter)['buildGuardedWhereClause'](filter, paramsForSelect);
618
621
  const selectSql = `SELECT _id, data FROM "${this.name}" WHERE ${whereClause}`;
619
622
  const rowsToUpdate = await this.db.all(selectSql, paramsForSelect);
620
623
  if (rowsToUpdate.length === 0) {
@@ -712,7 +715,10 @@ export class MongoLiteCollection {
712
715
  const value = opArgs[path];
713
716
  const currentValue = this.getNestedValue(currentDoc, path);
714
717
  const arr = Array.isArray(currentValue) ? currentValue : [];
715
- const items = typeof value === 'object' && value !== null && '$each' in value && Array.isArray(value.$each)
718
+ const items = typeof value === 'object' &&
719
+ value !== null &&
720
+ '$each' in value &&
721
+ Array.isArray(value.$each)
716
722
  ? value.$each
717
723
  : [value];
718
724
  let changed = false;
@@ -1036,7 +1042,7 @@ export class MongoLiteCollection {
1036
1042
  async deleteOne(filter) {
1037
1043
  await this.ensureTable();
1038
1044
  const paramsForDelete = [];
1039
- const whereClause = new FindCursor(this.db, this.name, filter)['buildWhereClause'](filter, paramsForDelete);
1045
+ const whereClause = new FindCursor(this.db, this.name, filter)['buildGuardedWhereClause'](filter, paramsForDelete);
1040
1046
  // Get the number of documents that would be deleted
1041
1047
  const countSql = `SELECT COUNT(*) as count FROM "${this.name}" WHERE ${whereClause} LIMIT 1`;
1042
1048
  const countResult = await this.db.get(countSql, paramsForDelete);
@@ -1065,7 +1071,7 @@ export class MongoLiteCollection {
1065
1071
  async deleteMany(filter) {
1066
1072
  await this.ensureTable();
1067
1073
  const paramsForDelete = [];
1068
- const whereClause = new FindCursor(this.db, this.name, filter)['buildWhereClause'](filter, paramsForDelete);
1074
+ const whereClause = new FindCursor(this.db, this.name, filter)['buildGuardedWhereClause'](filter, paramsForDelete);
1069
1075
  // Get the number of documents that would be deleted
1070
1076
  const countSql = `SELECT COUNT(*) as count FROM "${this.name}" WHERE ${whereClause}`;
1071
1077
  const countResult = await this.db.get(countSql, paramsForDelete);
@@ -1091,11 +1097,40 @@ export class MongoLiteCollection {
1091
1097
  async countDocuments(filter = {}) {
1092
1098
  await this.ensureTable();
1093
1099
  const paramsForCount = [];
1094
- const whereClause = new FindCursor(this.db, this.name, filter)['buildWhereClause'](filter, paramsForCount);
1100
+ const whereClause = new FindCursor(this.db, this.name, filter)['buildGuardedWhereClause'](filter, paramsForCount);
1095
1101
  const countSql = `SELECT COUNT(*) as count FROM "${this.name}" WHERE ${whereClause}`;
1096
1102
  const result = await this.db.get(countSql, paramsForCount);
1097
1103
  return result?.count || 0;
1098
1104
  }
1105
+ /**
1106
+ * Finds rows whose stored `data` column is not valid JSON.
1107
+ *
1108
+ * Filtered queries deliberately skip these rows — see
1109
+ * `FindCursor.buildGuardedWhereClause` — so that one corrupted document can't
1110
+ * make the whole collection unqueryable. That keeps reads working, but it also
1111
+ * means such rows quietly stop appearing in results. This is the way to find
1112
+ * them so they can be repaired or deleted (`deleteOne({ _id })` works on them,
1113
+ * since `_id` lookups don't go through json1 functions).
1114
+ *
1115
+ * Intended for integrity checks and ops tooling rather than hot paths: it scans
1116
+ * the table and returns the raw column text, not parsed documents.
1117
+ *
1118
+ * @returns The `_id` and raw stored text of every invalid row.
1119
+ */
1120
+ async findInvalidJson() {
1121
+ await this.ensureTable();
1122
+ return this.db.all(`SELECT _id, data FROM "${this.name}" WHERE json_valid(data) = 0`);
1123
+ }
1124
+ /**
1125
+ * Counts rows whose stored `data` column is not valid JSON.
1126
+ * Cheap enough to run on a schedule as a health check.
1127
+ * @see findInvalidJson
1128
+ */
1129
+ async countInvalidJson() {
1130
+ await this.ensureTable();
1131
+ const result = await this.db.get(`SELECT COUNT(*) as count FROM "${this.name}" WHERE json_valid(data) = 0`);
1132
+ return result?.count || 0;
1133
+ }
1099
1134
  /**
1100
1135
  * Returns the number of documents in the collection.
1101
1136
  * This is an estimate and may not reflect the exact count in concurrent environments.
@@ -1124,9 +1159,7 @@ export class MongoLiteCollection {
1124
1159
  return null;
1125
1160
  }
1126
1161
  // Update by _id when available to ensure we modify the exact document we found
1127
- const updateFilter = existingId !== undefined && existingId !== null
1128
- ? { _id: existingId }
1129
- : filter;
1162
+ const updateFilter = existingId !== undefined && existingId !== null ? { _id: existingId } : filter;
1130
1163
  const updateResult = await this.updateOne(updateFilter, update, { upsert });
1131
1164
  if (returnDocument === 'after') {
1132
1165
  const targetId = updateResult.upsertedId ?? existingId;
@@ -1487,7 +1520,8 @@ export class MongoLiteCollection {
1487
1520
  const nums = groupDocs
1488
1521
  .map((doc) => this.getNestedValue(doc, fieldName))
1489
1522
  .filter((v) => typeof v === 'number');
1490
- groupResult[field] = nums.length > 0 ? nums.reduce((a, b) => a + b, 0) / nums.length : null;
1523
+ groupResult[field] =
1524
+ nums.length > 0 ? nums.reduce((a, b) => a + b, 0) / nums.length : null;
1491
1525
  }
1492
1526
  break;
1493
1527
  }
@@ -1497,7 +1531,8 @@ export class MongoLiteCollection {
1497
1531
  const vals = groupDocs
1498
1532
  .map((doc) => this.getNestedValue(doc, fieldName))
1499
1533
  .filter((v) => v !== undefined && v !== null);
1500
- groupResult[field] = vals.length > 0 ? vals.reduce((a, b) => (a < b ? a : b)) : null;
1534
+ groupResult[field] =
1535
+ vals.length > 0 ? vals.reduce((a, b) => (a < b ? a : b)) : null;
1501
1536
  }
1502
1537
  break;
1503
1538
  }
@@ -1507,7 +1542,8 @@ export class MongoLiteCollection {
1507
1542
  const vals = groupDocs
1508
1543
  .map((doc) => this.getNestedValue(doc, fieldName))
1509
1544
  .filter((v) => v !== undefined && v !== null);
1510
- groupResult[field] = vals.length > 0 ? vals.reduce((a, b) => (a > b ? a : b)) : null;
1545
+ groupResult[field] =
1546
+ vals.length > 0 ? vals.reduce((a, b) => (a > b ? a : b)) : null;
1511
1547
  }
1512
1548
  break;
1513
1549
  }
@@ -1603,7 +1639,10 @@ export class MongoLiteCollection {
1603
1639
  if (key.startsWith('$'))
1604
1640
  continue;
1605
1641
  const docValue = this.getNestedValue(doc, key);
1606
- if (typeof value === 'object' && value !== null && !(value instanceof RegExp) && !(value instanceof Date)) {
1642
+ if (typeof value === 'object' &&
1643
+ value !== null &&
1644
+ !(value instanceof RegExp) &&
1645
+ !(value instanceof Date)) {
1607
1646
  const ops = value;
1608
1647
  const hasOps = Object.keys(ops).some((k) => k.startsWith('$'));
1609
1648
  if (hasOps) {