lines-db 0.0.0-stage → 0.15.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.
package/bin/cli.mjs ADDED
@@ -0,0 +1,3499 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire, register } from "node:module";
3
+ import { access, chmod, link, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
4
+ import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve } from "node:path";
5
+ import { createHash, randomBytes } from "node:crypto";
6
+ import { pathToFileURL } from "node:url";
7
+ import { styleText } from "node:util";
8
+ import { z } from "zod";
9
+ import { arg, defineCommand, runMain } from "@politty/zod";
10
+ import { runInNewContext } from "node:vm";
11
+ import { spawn } from "node:child_process";
12
+ //#region \0rolldown/runtime.js
13
+ var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
14
+ //#endregion
15
+ //#region src/schema-extensions.ts
16
+ /**
17
+ * Supported schema file extensions, in priority order.
18
+ * The first match wins when discovering schema files.
19
+ */
20
+ const SCHEMA_EXTENSIONS = [
21
+ ".schema.ts",
22
+ ".schema.mts",
23
+ ".schema.cts"
24
+ ];
25
+ /**
26
+ * Map from schema extensions to their JavaScript import counterparts.
27
+ */
28
+ const SCHEMA_TO_JS_IMPORT_MAP = {
29
+ ".schema.ts": ".schema.js",
30
+ ".schema.mts": ".schema.mjs",
31
+ ".schema.cts": ".schema.cjs"
32
+ };
33
+ /**
34
+ * Try each supported schema extension and return the full path of the first
35
+ * one that exists on disk. Returns undefined if none is found.
36
+ */
37
+ async function findSchemaFile(dir, tableName) {
38
+ for (const ext of SCHEMA_EXTENSIONS) {
39
+ const candidate = join(dir, `${tableName}${ext}`);
40
+ try {
41
+ await access(candidate);
42
+ return candidate;
43
+ } catch {}
44
+ }
45
+ }
46
+ /**
47
+ * Synchronously find a schema file among directory entries.
48
+ * Returns the full path of the first match, or undefined.
49
+ */
50
+ function findSchemaFileInEntries(dataDirPath, tableName, entries) {
51
+ for (const ext of SCHEMA_EXTENSIONS) {
52
+ const candidateName = `${tableName}${ext}`;
53
+ if (entries.some((e) => e.isFile() && e.name === candidateName)) return join(dataDirPath, candidateName);
54
+ }
55
+ }
56
+ /**
57
+ * Rewrite a TypeScript path to its JavaScript counterpart for ESM imports.
58
+ * ".schema.ts" -> ".schema.js", ".schema.mts" -> ".schema.mjs", ".schema.cts" -> ".schema.cjs"
59
+ */
60
+ function rewriteExtensionForImport(filePath) {
61
+ for (const [tsExt, jsExt] of Object.entries(SCHEMA_TO_JS_IMPORT_MAP)) if (filePath.endsWith(tsExt)) return filePath.slice(0, -tsExt.length) + jsExt;
62
+ return filePath;
63
+ }
64
+ //#endregion
65
+ //#region src/type-generator.ts
66
+ var TypeGenerator = class {
67
+ dataDir;
68
+ projectRoot;
69
+ outputFile;
70
+ dataDirPath;
71
+ constructor(options) {
72
+ const envProjectRoot = process.env.LINES_DB_TEST_PROJECT_ROOT;
73
+ this.projectRoot = envProjectRoot !== void 0 ? envProjectRoot : options.projectRoot || process.cwd();
74
+ this.dataDir = options.dataDir;
75
+ this.dataDirPath = isAbsolute(this.dataDir) ? this.dataDir : join(this.projectRoot, this.dataDir);
76
+ this.outputFile = options.output ? isAbsolute(options.output) ? options.output : join(this.projectRoot, options.output) : join(this.dataDirPath, "db.ts");
77
+ }
78
+ /**
79
+ * Generate types file from JSONL files and their optional schema files.
80
+ */
81
+ async generate() {
82
+ const tables = await this.findTables();
83
+ if (tables.length === 0) throw new Error(`No JSONL files found in ${this.dataDirPath}. Place one or more *.jsonl files in the directory.`);
84
+ const content = this.generateTypeDeclarations(tables);
85
+ const outputDir = dirname(this.outputFile);
86
+ await mkdir(outputDir, { recursive: true });
87
+ await writeFile(this.outputFile, content, "utf-8");
88
+ console.log(`Generated types at ${this.outputFile}`);
89
+ return this.outputFile;
90
+ }
91
+ /**
92
+ * Find all *.jsonl files and check if they have corresponding *.schema.ts files
93
+ */
94
+ async findTables() {
95
+ try {
96
+ const entries = await readdir(this.dataDirPath, { withFileTypes: true });
97
+ const tables = [];
98
+ for (const entry of entries) if (entry.isFile() && entry.name.endsWith(".jsonl")) {
99
+ const tableName = basename(entry.name, ".jsonl");
100
+ const schemaFilePath = findSchemaFileInEntries(this.dataDirPath, tableName, entries);
101
+ tables.push({
102
+ tableName,
103
+ schemaFile: schemaFilePath
104
+ });
105
+ }
106
+ return tables;
107
+ } catch (error) {
108
+ if (error.code === "ENOENT") throw new Error(`Data directory not found: ${this.dataDirPath}. Set lines-db.dataDir to the correct location.`);
109
+ throw error;
110
+ }
111
+ }
112
+ /**
113
+ * Generate type declaration content
114
+ */
115
+ generateTypeDeclarations(tables) {
116
+ const imports = [];
117
+ const tableEntries = [];
118
+ const usedAliases = /* @__PURE__ */ new Set();
119
+ for (const table of tables) {
120
+ const tableKey = this.formatTableKey(table.tableName);
121
+ if (table.schemaFile) {
122
+ const schemaIdentifier = this.createSchemaIdentifier(table.tableName, usedAliases);
123
+ usedAliases.add(schemaIdentifier);
124
+ let relativePath = rewriteExtensionForImport(relative(join(this.outputFile, ".."), table.schemaFile).replace(/\\/g, "/"));
125
+ if (!relativePath.startsWith(".")) relativePath = "./" + relativePath;
126
+ imports.push(`import { schema as ${schemaIdentifier} } from '${relativePath}';`);
127
+ tableEntries.push(` ${tableKey}: InferOutput<typeof ${schemaIdentifier}>;`);
128
+ } else tableEntries.push(` ${tableKey}: Record<string, unknown>;`);
129
+ }
130
+ return `// Auto-generated by lines-db
131
+ // Do not edit this file manually
132
+
133
+ ${imports.length > 0 ? `${imports.join("\n")}\n` : ""}import type { DatabaseConfig${imports.length > 0 ? ", InferOutput" : ""} } from 'lines-db';
134
+ import { fileURLToPath } from 'node:url';
135
+ import { dirname } from 'node:path';
136
+
137
+ const __filename = fileURLToPath(import.meta.url);
138
+ const __dirname = dirname(__filename);
139
+
140
+ export type Tables = {
141
+ ${tableEntries.join("\n")}
142
+ };
143
+
144
+ export const config: DatabaseConfig<Tables> = {
145
+ dataDir: __dirname,
146
+ };
147
+ `;
148
+ }
149
+ createSchemaIdentifier(tableName, usedAliases) {
150
+ let base = sanitizeIdentifier(toCamelCase(tableName)) || "table";
151
+ if (!/^[A-Za-z_$]/.test(base)) base = `_${base}`;
152
+ let candidate = `${base}Schema`;
153
+ let suffix = 1;
154
+ while (usedAliases.has(candidate)) candidate = `${base}${++suffix}Schema`;
155
+ return candidate;
156
+ }
157
+ formatTableKey(tableName) {
158
+ if (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(tableName)) return tableName;
159
+ return `'${tableName.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
160
+ }
161
+ };
162
+ function toCamelCase(value) {
163
+ const parts = value.split(/[^A-Za-z0-9]+/).filter(Boolean).map((part) => part.toLowerCase());
164
+ if (parts.length === 0) return value;
165
+ const [first, ...rest] = parts;
166
+ return first + rest.map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
167
+ }
168
+ function sanitizeIdentifier(value) {
169
+ return value.replace(/[^A-Za-z0-9_$]/g, "");
170
+ }
171
+ //#endregion
172
+ //#region src/runtime.ts
173
+ function detectRuntime() {
174
+ if (typeof process !== "undefined" && process.versions && process.versions.node) return "node";
175
+ return "unknown";
176
+ }
177
+ const RUNTIME = detectRuntime();
178
+ //#endregion
179
+ //#region src/sqlite-adapter.ts
180
+ /**
181
+ * SQLite adapter for Node.js
182
+ */
183
+ /**
184
+ * Create a SQLite database instance for Node.js
185
+ */
186
+ function createDatabase(path = ":memory:") {
187
+ if (RUNTIME === "node") return createNodeDatabase(path);
188
+ else throw new Error(`Unsupported runtime: ${RUNTIME}`);
189
+ }
190
+ /**
191
+ * Create a Node.js SQLite database
192
+ */
193
+ function createNodeDatabase(path) {
194
+ const { DatabaseSync } = __require("node:sqlite");
195
+ const db = new DatabaseSync(path);
196
+ db.exec("PRAGMA foreign_keys = ON");
197
+ return {
198
+ prepare(sql) {
199
+ const stmt = db.prepare(sql);
200
+ return {
201
+ run(...params) {
202
+ return stmt.run(...params);
203
+ },
204
+ get(...params) {
205
+ return stmt.get(...params);
206
+ },
207
+ all(...params) {
208
+ return stmt.all(...params);
209
+ }
210
+ };
211
+ },
212
+ exec(sql) {
213
+ db.exec(sql);
214
+ },
215
+ close() {
216
+ db.close();
217
+ }
218
+ };
219
+ }
220
+ //#endregion
221
+ //#region src/result.ts
222
+ function ok(value) {
223
+ return {
224
+ ok: true,
225
+ value
226
+ };
227
+ }
228
+ function err(error) {
229
+ return {
230
+ ok: false,
231
+ error
232
+ };
233
+ }
234
+ /** Normalize a thrown value (which may not be an Error) into an Error. */
235
+ function toError(value) {
236
+ return value instanceof Error ? value : new Error(String(value));
237
+ }
238
+ /** Unwrap a Result, throwing its error when it is not ok. */
239
+ function unwrap(result) {
240
+ if (result.ok) return result.value;
241
+ throw result.error;
242
+ }
243
+ //#endregion
244
+ //#region src/jsonl-reader.ts
245
+ /** Fingerprint of a JSONL file's content, to tell whether the file changed since it was read */
246
+ function hashJsonlContent(content) {
247
+ return createHash("sha256").update(content).digest("hex");
248
+ }
249
+ var JsonlReader = class {
250
+ static overrides = null;
251
+ /**
252
+ * Temporarily override the data returned for specific JSONL files.
253
+ * Useful for scenarios like migration validation where in-memory data should be used.
254
+ */
255
+ static async withOverrides(overrides, fn) {
256
+ const normalized = /* @__PURE__ */ new Map();
257
+ for (const [filePath, rows] of overrides) normalized.set(normalize(filePath), rows);
258
+ const previousOverrides = this.overrides;
259
+ this.overrides = normalized;
260
+ try {
261
+ return await fn();
262
+ } finally {
263
+ this.overrides = previousOverrides;
264
+ }
265
+ }
266
+ /**
267
+ * Read JSONL file and parse each line as JSON
268
+ */
269
+ static async read(filePath) {
270
+ const result = await this.readSnapshot(filePath);
271
+ return result.ok ? result.value.rows : result;
272
+ }
273
+ /**
274
+ * Read JSONL file like {@link read}, along with a hash of the content the rows were parsed from.
275
+ * The hash is there even when the content does not parse.
276
+ */
277
+ static async readSnapshot(filePath) {
278
+ const overrideRows = this.overrides?.get(normalize(filePath));
279
+ if (overrideRows) return ok({
280
+ rows: ok(overrideRows.map((row) => JSON.parse(JSON.stringify(row)))),
281
+ contentHash: void 0
282
+ });
283
+ let content;
284
+ try {
285
+ content = await readFile(filePath, "utf-8");
286
+ } catch (error) {
287
+ return err(toError(error));
288
+ }
289
+ return ok({
290
+ rows: this.parse(filePath, content),
291
+ contentHash: hashJsonlContent(content)
292
+ });
293
+ }
294
+ static parse(filePath, content) {
295
+ const rawLines = (content.startsWith("") ? content.slice(1) : content).split("\n");
296
+ const rows = [];
297
+ for (let i = 0; i < rawLines.length; i++) {
298
+ const line = rawLines[i].endsWith("\r") ? rawLines[i].slice(0, -1) : rawLines[i];
299
+ if (line.trim().length === 0) continue;
300
+ const fail = (message, cause) => {
301
+ const parseError = new Error(message, { cause });
302
+ parseError.name = "JsonlParseError";
303
+ parseError.file = filePath;
304
+ parseError.line = i + 1;
305
+ return err(parseError);
306
+ };
307
+ let value;
308
+ try {
309
+ value = JSON.parse(line);
310
+ } catch (error) {
311
+ return fail(`Failed to parse JSON line: ${line}`, error);
312
+ }
313
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return fail(`A JSONL line holds a row, which is a JSON object: ${line}`);
314
+ rows.push(value);
315
+ }
316
+ return ok(rows);
317
+ }
318
+ /**
319
+ * Infer schema from JSONL data
320
+ */
321
+ static inferSchema(tableName, data) {
322
+ if (data.length === 0) return err(/* @__PURE__ */ new Error("Cannot infer schema from empty data"));
323
+ const columnTypes = /* @__PURE__ */ new Map();
324
+ const presence = /* @__PURE__ */ new Map();
325
+ const booleanColumns = /* @__PURE__ */ new Set();
326
+ const nonBooleanColumns = /* @__PURE__ */ new Set();
327
+ for (const row of data) for (const [key, value] of Object.entries(row)) {
328
+ if (!columnTypes.has(key)) columnTypes.set(key, /* @__PURE__ */ new Set());
329
+ columnTypes.get(key).add(this.inferType(value));
330
+ presence.set(key, (presence.get(key) ?? 0) + 1);
331
+ if (typeof value === "boolean") booleanColumns.add(key);
332
+ else if (value !== null) nonBooleanColumns.add(key);
333
+ }
334
+ const columns = [];
335
+ for (const [columnName, types] of columnTypes.entries()) {
336
+ const typeArray = Array.from(types);
337
+ let sqlType = "TEXT";
338
+ if (typeArray.length === 1) sqlType = typeArray[0];
339
+ else if (typeArray.every((t) => t === "INTEGER" || t === "REAL")) sqlType = "REAL";
340
+ else if (!typeArray.includes("NULL")) sqlType = "TEXT";
341
+ else if (typeArray.length === 2 && typeArray.includes("NULL")) sqlType = typeArray.find((t) => t !== "NULL");
342
+ const isBooleanColumn = booleanColumns.has(columnName) && !nonBooleanColumns.has(columnName);
343
+ columns.push({
344
+ name: columnName,
345
+ type: sqlType,
346
+ notNull: !typeArray.includes("NULL") && presence.get(columnName) === data.length,
347
+ valueType: isBooleanColumn ? "boolean" : void 0
348
+ });
349
+ }
350
+ const idColumn = columns.find((col) => col.name === "id");
351
+ if (idColumn) idColumn.primaryKey = true;
352
+ return ok({
353
+ name: tableName,
354
+ columns
355
+ });
356
+ }
357
+ static inferType(value) {
358
+ if (value === null || value === void 0) return "NULL";
359
+ if (typeof value === "number") return Number.isInteger(value) ? "INTEGER" : "REAL";
360
+ if (typeof value === "string") return "TEXT";
361
+ if (typeof value === "boolean") return "INTEGER";
362
+ if (typeof value === "object") return "JSON";
363
+ return "TEXT";
364
+ }
365
+ };
366
+ //#endregion
367
+ //#region src/jsonl-writer.ts
368
+ var JsonlWriter = class {
369
+ /**
370
+ * Write data to JSONL file
371
+ */
372
+ static async write(filePath, data) {
373
+ await writeFile(filePath, this.serialize(data), "utf-8");
374
+ }
375
+ /**
376
+ * The content {@link write} writes for the data
377
+ */
378
+ static serialize(data) {
379
+ return data.map((obj) => JSON.stringify(obj)).join("\n") + "\n";
380
+ }
381
+ /**
382
+ * Append data to JSONL file
383
+ */
384
+ static async append(filePath, data) {
385
+ const { readFile, writeFile } = await import("node:fs/promises");
386
+ try {
387
+ const existing = await readFile(filePath, "utf-8");
388
+ const lines = data.map((obj) => JSON.stringify(obj)).join("\n");
389
+ await writeFile(filePath, existing.trim() + "\n" + lines + "\n", "utf-8");
390
+ } catch (error) {
391
+ if (error.code === "ENOENT") await this.write(filePath, data);
392
+ else throw error;
393
+ }
394
+ }
395
+ };
396
+ //#endregion
397
+ //#region src/replace-file.ts
398
+ async function replaceFile(file, write, expected) {
399
+ const suffix = randomBytes(12).toString("hex");
400
+ const temporary = `${file}.${suffix}.tmp`;
401
+ const backup = `${file}.${suffix}.backup`;
402
+ let moved = false;
403
+ const conflict = () => Object.assign(/* @__PURE__ */ new Error(`JSONL file '${file}' changed during the write`), {
404
+ name: "JsonlConflictError",
405
+ file
406
+ });
407
+ try {
408
+ if (write) {
409
+ await write(temporary);
410
+ const mode = await stat(file).catch((error) => {
411
+ if (error.code === "ENOENT") return void 0;
412
+ throw error;
413
+ });
414
+ if (mode) await chmod(temporary, mode.mode & 4095);
415
+ }
416
+ if (expected !== void 0) {
417
+ await rename(file, backup).catch((error) => {
418
+ if (error.code === "ENOENT") throw conflict();
419
+ throw error;
420
+ });
421
+ moved = true;
422
+ if (await readFile(backup, "utf8") !== expected) throw conflict();
423
+ }
424
+ if (write) await link(temporary, file).catch((error) => {
425
+ if (error.code === "EEXIST") throw conflict();
426
+ throw error;
427
+ });
428
+ const cleanBackup = moved;
429
+ moved = false;
430
+ if (cleanBackup) await rm(backup).catch(() => {});
431
+ } catch (error) {
432
+ if (moved) try {
433
+ await link(backup, file);
434
+ moved = false;
435
+ await rm(backup).catch(() => {});
436
+ } catch (restoreError) {
437
+ if (error instanceof Error) {
438
+ error.message += `; original content remains in '${backup}' because it could not be restored`;
439
+ if (write) error.message += `; staged content remains in '${temporary}'`;
440
+ } else throw new Error(`Original content remains in '${backup}' because it could not be restored`, { cause: restoreError });
441
+ }
442
+ throw error;
443
+ } finally {
444
+ if (!moved) await rm(temporary, { force: true }).catch(() => {});
445
+ }
446
+ }
447
+ //#endregion
448
+ //#region src/schema-loader.ts
449
+ var SchemaLoader = class {
450
+ /**
451
+ * Check if a schema file exists for a table
452
+ */
453
+ static async hasSchema(jsonlPath, schemaDir) {
454
+ return await findSchemaFile(schemaDir ?? dirname(jsonlPath), basename(jsonlPath, ".jsonl")) !== void 0;
455
+ }
456
+ /**
457
+ * Load a validation schema file for a table
458
+ * Requires ${tableName}.schema.{ts,mts,cts} to exist in schemaDir, or alongside the JSONL file when omitted
459
+ */
460
+ static async loadSchema(jsonlPath, schemaDir) {
461
+ const dir = schemaDir ?? dirname(jsonlPath);
462
+ const tableName = basename(jsonlPath, ".jsonl");
463
+ const schemaPath = await findSchemaFile(dir, tableName);
464
+ if (!schemaPath) throw new Error(`Schema file not found for table '${tableName}'. Expected one of: ${SCHEMA_EXTENSIONS.map((ext) => `${tableName}${ext}`).join(", ")}`);
465
+ try {
466
+ const module = await import(`${pathToFileURL(schemaPath).href}?t=${Date.now()}`);
467
+ const schema = module.default || module.schema;
468
+ if (schema && this.isStandardSchema(schema)) return schema;
469
+ throw new Error(`Schema file ${schemaPath} does not export a valid StandardSchema`);
470
+ } catch (error) {
471
+ throw new Error(`Failed to load schema for table '${tableName}' from ${schemaPath}: ${error instanceof Error ? error.message : String(error)}`, { cause: error instanceof Error ? error : void 0 });
472
+ }
473
+ }
474
+ /**
475
+ * Check if an object implements the StandardSchema interface
476
+ */
477
+ static isStandardSchema(obj) {
478
+ if (!obj || typeof obj !== "object") return false;
479
+ const standard = obj["~standard"];
480
+ if (!standard || typeof standard !== "object") return false;
481
+ const standardObj = standard;
482
+ return standardObj.version === 1 && typeof standardObj.vendor === "string" && typeof standardObj.validate === "function";
483
+ }
484
+ };
485
+ //#endregion
486
+ //#region src/directory-scanner.ts
487
+ var DirectoryScanner = class {
488
+ /**
489
+ * Scan directories for JSONL files and create table configurations.
490
+ * A table found in several directories lists its files in the order the directories are given.
491
+ */
492
+ static async scanDirectory(dataDir) {
493
+ const dataDirs = typeof dataDir === "string" ? [dataDir] : dataDir;
494
+ const jsonlPathsByTable = /* @__PURE__ */ new Map();
495
+ for (const dir of dataDirs) {
496
+ let files;
497
+ try {
498
+ files = await readdir(dir);
499
+ } catch (error) {
500
+ throw new Error(`Failed to scan directory ${dir}: ${error instanceof Error ? error.message : String(error)}`);
501
+ }
502
+ for (const file of files) if (extname(file) === ".jsonl") {
503
+ const tableName = basename(file, ".jsonl");
504
+ const jsonlPaths = jsonlPathsByTable.get(tableName) ?? [];
505
+ jsonlPaths.push(join(dir, file));
506
+ jsonlPathsByTable.set(tableName, jsonlPaths);
507
+ }
508
+ }
509
+ if (jsonlPathsByTable.size === 0) console.warn(`Warning: No JSONL files found in directory: ${dataDirs.join(", ")}`);
510
+ const tables = /* @__PURE__ */ new Map();
511
+ for (const [tableName, jsonlPaths] of jsonlPathsByTable) tables.set(tableName, {
512
+ jsonlPath: jsonlPaths[0],
513
+ jsonlPaths,
514
+ autoInferSchema: true
515
+ });
516
+ return tables;
517
+ }
518
+ };
519
+ //#endregion
520
+ //#region src/schema.ts
521
+ /**
522
+ * Check if a schema has backward transformation
523
+ */
524
+ function hasBackward(schema) {
525
+ return "backward" in schema && typeof schema.backward === "function";
526
+ }
527
+ //#endregion
528
+ //#region src/merge-fields.ts
529
+ /**
530
+ * Lay the named fields of a computed row over the line a JSONL file already holds.
531
+ *
532
+ * A field the line did not have is inserted where the schema declares it rather than appended, so a
533
+ * filled-in `id` lands at the front of the line the way a hand-written row has it. No key the line
534
+ * already had moves, and a key the schema does not declare stays behind the declared ones.
535
+ *
536
+ * @param line - The row as the JSONL file holds it
537
+ * @param computed - The row a schema computed from it, which the named fields are taken from. Only its
538
+ * own fields count: a field the schema does not produce is left to the line even when a name like
539
+ * `toString` would resolve to something on `Object.prototype`. A field it holds as `undefined` is
540
+ * left to the line as well.
541
+ * @param options - The fields to take, and the order they are declared in
542
+ * @returns A new row: the line, with the named fields written into it
543
+ *
544
+ * @example
545
+ * // line: {"name":"Alice","note":"check"}
546
+ * // computed: {"id":"018f…","name":"Alice","createdAt":"2026-…"}
547
+ * mergeFields(line, computed, { fields: ['id', 'createdAt'] });
548
+ * // {"id":"018f…","name":"Alice","createdAt":"2026-…","note":"check"}
549
+ */
550
+ function mergeFields(line, computed, options) {
551
+ const rank = /* @__PURE__ */ new Map();
552
+ for (const key of options.keyOrder ?? Object.keys(computed)) if (!rank.has(key)) rank.set(key, rank.size);
553
+ const rankOf = (key) => rank.get(key) ?? Number.MAX_SAFE_INTEGER;
554
+ const written = /* @__PURE__ */ new Map();
555
+ for (const field of options.fields) if (Object.hasOwn(computed, field) && computed[field] !== void 0) written.set(field, computed[field]);
556
+ const inserted = Array.from(written.keys()).filter((field) => !Object.hasOwn(line, field)).sort((a, b) => rankOf(a) - rankOf(b));
557
+ const entries = [];
558
+ for (const key of Object.keys(line)) {
559
+ while (inserted.length > 0 && rankOf(inserted[0]) < rankOf(key)) {
560
+ const field = inserted.shift();
561
+ entries.push([field, written.get(field)]);
562
+ }
563
+ entries.push([key, written.has(key) ? written.get(key) : line[key]]);
564
+ }
565
+ for (const field of inserted) entries.push([field, written.get(field)]);
566
+ return Object.fromEntries(entries);
567
+ }
568
+ /**
569
+ * The row with the fields its line holds that the table has no column for - a schema that strips
570
+ * unknown keys lets them through - kept where the line holds them, so writing back does not drop them
571
+ */
572
+ function keepUnknownFields(line, row, columns) {
573
+ const unknown = Object.keys(line).filter((key) => !columns.has(key) && !Object.hasOwn(row, key));
574
+ if (unknown.length === 0) return row;
575
+ const entries = [];
576
+ for (const key of Object.keys(line)) if (Object.hasOwn(row, key)) entries.push([key, row[key]]);
577
+ else if (unknown.includes(key)) entries.push([key, line[key]]);
578
+ for (const key of Object.keys(row)) if (!Object.hasOwn(line, key)) entries.push([key, row[key]]);
579
+ return Object.fromEntries(entries);
580
+ }
581
+ //#endregion
582
+ //#region src/sql-statements.ts
583
+ const TRIGGER_DEFINITION = /^\s*CREATE\s+(?:TEMP(?:ORARY)?\s+)?TRIGGER\b/i;
584
+ const CLOSER = {
585
+ "'": "'",
586
+ "\"": "\"",
587
+ "`": "`",
588
+ "[": "]"
589
+ };
590
+ /**
591
+ * Split SQL text into its statements at `;`, the way SQLite reads it: a `;` inside a comment or quoted
592
+ * text does not end a statement, and a comment is left out as the whitespace it is
593
+ */
594
+ function splitStatements(sql) {
595
+ const statements = [];
596
+ let current = "";
597
+ let i = 0;
598
+ while (i < sql.length) {
599
+ const char = sql[i];
600
+ if (char === "-" && sql[i + 1] === "-") {
601
+ const end = sql.indexOf("\n", i);
602
+ i = end === -1 ? sql.length : end;
603
+ current += " ";
604
+ } else if (char === "/" && sql[i + 1] === "*") {
605
+ const end = sql.indexOf("*/", i + 2);
606
+ i = end === -1 ? sql.length : end + 2;
607
+ current += " ";
608
+ } else if (char in CLOSER) {
609
+ const end = sql.indexOf(CLOSER[char], i + 1);
610
+ const stop = end === -1 ? sql.length : end + 1;
611
+ current += sql.slice(i, stop);
612
+ i = stop;
613
+ } else if (char === ";" && !insideTriggerBody(current)) {
614
+ statements.push(current);
615
+ current = "";
616
+ i += 1;
617
+ } else {
618
+ current += char;
619
+ i += 1;
620
+ }
621
+ }
622
+ statements.push(current);
623
+ return statements.map((statement) => statement.trim()).filter((statement) => statement.length > 0);
624
+ }
625
+ /**
626
+ * Whether a `;` after this text is inside the body of a trigger, which only a `;` followed by `END` and
627
+ * another `;` closes. Only an END right after a `;` counts, as the END of a CASE in the body does not
628
+ */
629
+ function insideTriggerBody(statement) {
630
+ return TRIGGER_DEFINITION.test(statement) && !/;\s*END$/i.test(statement.trimEnd());
631
+ }
632
+ const READ_STATEMENTS = /* @__PURE__ */ new Set([
633
+ "SELECT",
634
+ "VALUES",
635
+ "WITH",
636
+ "EXPLAIN"
637
+ ]);
638
+ const READ_PRAGMAS_WITH_ARGUMENT = /* @__PURE__ */ new Set([
639
+ "table_info",
640
+ "table_xinfo",
641
+ "table_list",
642
+ "index_list",
643
+ "index_info",
644
+ "index_xinfo",
645
+ "foreign_key_list",
646
+ "foreign_key_check",
647
+ "integrity_check",
648
+ "quick_check",
649
+ "collation_list",
650
+ "database_list",
651
+ "function_list",
652
+ "module_list",
653
+ "pragma_list",
654
+ "compile_options"
655
+ ]);
656
+ const READ_PRAGMAS_BARE = /* @__PURE__ */ new Set([
657
+ "query_only",
658
+ "user_version",
659
+ "application_id",
660
+ "schema_version",
661
+ "foreign_keys",
662
+ "journal_mode",
663
+ "page_count",
664
+ "page_size",
665
+ "freelist_count",
666
+ "encoding",
667
+ "data_version"
668
+ ]);
669
+ const PRAGMA_NAME = String.raw`(?:\w+|"[^"]*"|'[^']*'|\x60[^\x60]*\x60|\[[^\]]*\])`;
670
+ const PRAGMA_STATEMENT = new RegExp(String.raw`^PRAGMA\s+(?:${PRAGMA_NAME}\s*\.\s*)?(${PRAGMA_NAME})\s*(\(.*\))?$`, "is");
671
+ /**
672
+ * Whether a statement, as {@link splitStatements} returns it, only reads. Closed by default: whatever is
673
+ * not known to read is refused, so a statement or pragma added to SQLite later is refused too. A WITH
674
+ * can wrap a write, which the read-only mode of the connection is left to refuse
675
+ */
676
+ function isReadOnlyStatement(statement) {
677
+ const keyword = /^[A-Za-z]+/.exec(statement)?.[0]?.toUpperCase();
678
+ if (keyword === void 0) return false;
679
+ if (READ_STATEMENTS.has(keyword)) return true;
680
+ if (keyword !== "PRAGMA") return false;
681
+ const match = PRAGMA_STATEMENT.exec(statement);
682
+ if (!match) return false;
683
+ const name = match[1].replace(/^["'`[]|["'`\]]$/g, "").toLowerCase();
684
+ const argument = match[2];
685
+ if (READ_PRAGMAS_WITH_ARGUMENT.has(name)) return true;
686
+ return READ_PRAGMAS_BARE.has(name) && argument === void 0;
687
+ }
688
+ //#endregion
689
+ //#region src/database.ts
690
+ function cloneFieldChanges(changes) {
691
+ return new Map(Array.from(changes, ([tableName, byRow]) => [tableName, new Map(Array.from(byRow, ([rowid, row]) => [rowid, {
692
+ set: new Set(row.set),
693
+ reset: new Set(row.reset),
694
+ inserted: row.inserted
695
+ }]))]));
696
+ }
697
+ /** Column alias a query reads a row's rowid under, next to its fields */
698
+ const ROWID_ALIAS = "__lines_db_rowid";
699
+ /** The fields a row given to an insert names, leaving out those it leaves undefined */
700
+ function givenFields(row) {
701
+ return Object.entries(row).filter(([, value]) => value !== void 0).map(([key]) => key);
702
+ }
703
+ /** Whether a value read from SQLite and one about to be stored are the same */
704
+ function sameStoredValue(stored, next) {
705
+ if (stored === null || stored === void 0 || next === null) return (stored ?? null) === next;
706
+ return String(stored) === String(next);
707
+ }
708
+ var LinesDB = class LinesDB {
709
+ db;
710
+ rowMovesTable = `__lines_db_moves_${randomBytes(12).toString("hex")}`;
711
+ config;
712
+ schemas = /* @__PURE__ */ new Map();
713
+ validationSchemas = /* @__PURE__ */ new Map();
714
+ tables = /* @__PURE__ */ new Map();
715
+ inTransaction = false;
716
+ syncQueue = /* @__PURE__ */ new Map();
717
+ /** The order a table's schema declares its fields in, as the rows it computes list them */
718
+ keyOrders = /* @__PURE__ */ new Map();
719
+ /** The row each rowid was inserted from, per table loaded with detailed validation */
720
+ rowOriginsByRowid = /* @__PURE__ */ new Map();
721
+ /**
722
+ * The fields set and reset on each row (by rowid) since its table was last written back: a line
723
+ * holds the fields a user wrote, so only what changed since it was written needs remembering
724
+ */
725
+ fieldChanges = /* @__PURE__ */ new Map();
726
+ /**
727
+ * The tables raw SQL may have changed since they were last written back: which fields it set is
728
+ * unknown, so their rows are written back whole
729
+ */
730
+ rawSqlTables = /* @__PURE__ */ new Set();
731
+ /** How many changes each table has seen, which tells a write-back whether one came after it read the rows */
732
+ changeGenerations = /* @__PURE__ */ new Map();
733
+ /**
734
+ * The lines read, by rowid, that hold a field the table has no column for: kept to write that field
735
+ * back, also once the row's primary key changed and its line can no longer be found by it
736
+ */
737
+ linesWithUnknownFields = /* @__PURE__ */ new Map();
738
+ /** Whether a transaction's callback has returned and its files are being written back */
739
+ transactionClosing = false;
740
+ /** Whether a transaction() call is past its guard but has not begun yet */
741
+ transactionStarting = false;
742
+ /** Whether the running call came in through the object the running transaction() callback receives */
743
+ viaTransactionObject = false;
744
+ /** Identifies the running transaction, so an object kept from an earlier one is not taken for its own */
745
+ transactionToken;
746
+ /** The tables changed in the running transaction, or 'all' once raw SQL may have changed any */
747
+ transactionChanges;
748
+ /** Hash of each JSONL file's content as this database last read or wrote it */
749
+ fileHashes = /* @__PURE__ */ new Map();
750
+ /**
751
+ * Hash of each JSONL file's content as this database last read or wrote it, kept for a table that
752
+ * failed to load too: unlike fileHashes, it only tells whether a file changed and guards no write
753
+ */
754
+ observedHashes = /* @__PURE__ */ new Map();
755
+ /** The JSONL files the data directories held when the tables were scanned */
756
+ scannedJsonlFiles = [];
757
+ /** Each table's schema file and a hash of its content as the tables were loaded, or '' for none */
758
+ schemaFileStates = /* @__PURE__ */ new Map();
759
+ constructor(config, dbPath) {
760
+ this.config = config;
761
+ this.db = createDatabase(dbPath ?? ":memory:");
762
+ }
763
+ static create(config, dbPath) {
764
+ return new LinesDB(config, dbPath);
765
+ }
766
+ /**
767
+ * Initialize database by loading all JSONL files or a specific table
768
+ * Uses dependency resolution to ensure foreign key references are loaded in correct order
769
+ * @param options Optional configuration for initialization
770
+ * @param options.tableName Optional table name to initialize. If not provided, initializes all tables
771
+ * @param options.detailedValidate If true, performs detailed validation by inserting rows one by one to catch constraint violations
772
+ * @param options.transform Optional transform function to apply to rows before validation (only applied to the specified tableName)
773
+ * @returns Result wrapping a ValidationResult with validation status, errors, and warnings
774
+ */
775
+ async initialize(options) {
776
+ try {
777
+ return ok(await this.initializeInternal(options));
778
+ } catch (error) {
779
+ return err(toError(error));
780
+ }
781
+ }
782
+ async initializeInternal(options) {
783
+ if (this.hasSeveralDataDirs() && !this.config.schemaDir) throw new Error("schemaDir is required when dataDir lists several directories: a data set directory does not hold the schemas of its tables");
784
+ this.db.exec("PRAGMA query_only = OFF");
785
+ try {
786
+ return await this.loadTables(options);
787
+ } finally {
788
+ if (this.isReadOnlyDataSet()) this.db.exec("PRAGMA query_only = ON");
789
+ }
790
+ }
791
+ async loadTables(options) {
792
+ const allErrors = [];
793
+ const allWarnings = [];
794
+ const allRowCounts = /* @__PURE__ */ new Map();
795
+ const tableName = options?.tableName;
796
+ const detailedValidate = options?.detailedValidate ?? false;
797
+ const transform = options?.transform;
798
+ this.tables = await DirectoryScanner.scanDirectory(this.config.dataDir);
799
+ this.scannedJsonlFiles = listJsonlFiles(this.tables);
800
+ this.observedHashes.clear();
801
+ this.schemaFileStates.clear();
802
+ for (const [name, config] of this.tables) this.schemaFileStates.set(name, await this.schemaFileState(name, config));
803
+ const tablesToLoad = tableName ? [tableName] : Array.from(this.tables.keys());
804
+ for (const tableNameToLoad of tablesToLoad) if (!this.tables.has(tableNameToLoad)) {
805
+ const dataDirs = [this.config.dataDir].flat().map((dir) => `'${dir}'`);
806
+ throw new Error(`Table '${tableNameToLoad}' not found in directory ${dataDirs.join(", ")}`);
807
+ }
808
+ const loadedTables = /* @__PURE__ */ new Set();
809
+ const loadingTables = /* @__PURE__ */ new Set();
810
+ const attemptedTables = /* @__PURE__ */ new Set();
811
+ const allDeferredForeignKeys = [];
812
+ for (const tableNameToLoad of tablesToLoad) if (!attemptedTables.has(tableNameToLoad)) {
813
+ const tableTransform = tableNameToLoad === tableName ? transform : void 0;
814
+ const { errors, warnings, rowCounts: tableRowCounts, deferredForeignKeys } = await this.loadTableWithDependencies(tableNameToLoad, loadedTables, loadingTables, attemptedTables, detailedValidate, tableTransform);
815
+ allErrors.push(...errors);
816
+ allWarnings.push(...warnings);
817
+ allDeferredForeignKeys.push(...deferredForeignKeys);
818
+ for (const [k, v] of tableRowCounts) allRowCounts.set(k, v);
819
+ }
820
+ if (detailedValidate && allDeferredForeignKeys.length > 0) for (const { tableName: tName, foreignKey: fk, filePath } of allDeferredForeignKeys) {
821
+ if (!loadedTables.has(fk.references.table)) continue;
822
+ const deferredErrors = this.validateDeferredForeignKey(tName, fk, filePath);
823
+ allErrors.push(...deferredErrors);
824
+ }
825
+ const tableResults = tablesToLoad.map((name) => {
826
+ const tableErrors = allErrors.filter((e) => e.tableName === name);
827
+ const tableWarnings = allWarnings.filter((w) => w.includes(`'${name}'`));
828
+ return {
829
+ tableName: name,
830
+ valid: tableErrors.length === 0,
831
+ rowCount: allRowCounts.get(name) ?? 0,
832
+ errors: tableErrors,
833
+ warnings: tableWarnings
834
+ };
835
+ });
836
+ return {
837
+ valid: allErrors.length === 0,
838
+ errors: allErrors,
839
+ warnings: allWarnings,
840
+ tableResults
841
+ };
842
+ }
843
+ /**
844
+ * Load a table and its dependencies recursively
845
+ */
846
+ async loadTableWithDependencies(tableName, loadedTables, loadingTables, attemptedTables, detailedValidate, transform) {
847
+ const errors = [];
848
+ const warnings = [];
849
+ const rowCounts = /* @__PURE__ */ new Map();
850
+ const deferredForeignKeys = [];
851
+ if (attemptedTables.has(tableName)) return {
852
+ errors,
853
+ warnings,
854
+ rowCounts,
855
+ deferredForeignKeys
856
+ };
857
+ attemptedTables.add(tableName);
858
+ if (loadingTables.has(tableName)) throw new Error(`Circular dependency detected for table '${tableName}'`);
859
+ const tableConfig = this.tables.get(tableName);
860
+ if (!tableConfig) throw new Error(`Table configuration not found for '${tableName}'`);
861
+ loadingTables.add(tableName);
862
+ try {
863
+ let foreignKeys;
864
+ try {
865
+ const { pathToFileURL } = await import("node:url");
866
+ const schemaPath = await this.findTableSchemaFile(tableName, tableConfig);
867
+ if (schemaPath) {
868
+ const schemaModule = await import(`${pathToFileURL(schemaPath).href}?t=${Date.now()}`);
869
+ foreignKeys = (schemaModule.schema || schemaModule.default)?.foreignKeys || schemaModule.foreignKeys;
870
+ }
871
+ } catch {}
872
+ if (foreignKeys && foreignKeys.length > 0) for (const fk of foreignKeys) {
873
+ const referencedTable = fk.references.table;
874
+ if (referencedTable === tableName) continue;
875
+ if (!attemptedTables.has(referencedTable)) {
876
+ if (this.tables.has(referencedTable)) {
877
+ const depResult = await this.loadTableWithDependencies(referencedTable, loadedTables, loadingTables, attemptedTables, detailedValidate, void 0);
878
+ errors.push(...depResult.errors);
879
+ warnings.push(...depResult.warnings);
880
+ deferredForeignKeys.push(...depResult.deferredForeignKeys);
881
+ for (const [k, v] of depResult.rowCounts) rowCounts.set(k, v);
882
+ } else throw new Error(`Foreign key reference to non-existent table '${referencedTable}' in table '${tableName}'`);
883
+ }
884
+ }
885
+ const failedDependencies = /* @__PURE__ */ new Set();
886
+ const circularDependencies = /* @__PURE__ */ new Set();
887
+ if (foreignKeys && foreignKeys.length > 0) {
888
+ for (const fk of foreignKeys) {
889
+ const referencedTable = fk.references.table;
890
+ if (referencedTable === tableName) continue;
891
+ if (attemptedTables.has(referencedTable) && !loadedTables.has(referencedTable)) {
892
+ if (loadingTables.has(referencedTable)) circularDependencies.add(referencedTable);
893
+ else failedDependencies.add(referencedTable);
894
+ }
895
+ }
896
+ if (failedDependencies.size > 0) for (const dep of failedDependencies) warnings.push(`Skipping foreign key validation for table '${tableName}': referenced table '${dep}' has validation errors`);
897
+ }
898
+ const allSkippedDependencies = /* @__PURE__ */ new Set([...failedDependencies, ...circularDependencies]);
899
+ const { loaded, rowCount, errors: loadErrors } = await this.loadTable(tableName, tableConfig, detailedValidate, transform, allSkippedDependencies);
900
+ errors.push(...loadErrors);
901
+ rowCounts.set(tableName, rowCount);
902
+ if (loaded) {
903
+ loadedTables.add(tableName);
904
+ if (foreignKeys && circularDependencies.size > 0) {
905
+ for (const fk of foreignKeys) if (circularDependencies.has(fk.references.table)) deferredForeignKeys.push({
906
+ tableName,
907
+ foreignKey: fk,
908
+ filePath: tableConfig.jsonlPath
909
+ });
910
+ }
911
+ } else {
912
+ warnings.push(`Table '${tableName}' was not loaded (no data or skipped)`);
913
+ this.tables.delete(tableName);
914
+ }
915
+ } finally {
916
+ loadingTables.delete(tableName);
917
+ }
918
+ return {
919
+ errors,
920
+ warnings,
921
+ rowCounts,
922
+ deferredForeignKeys
923
+ };
924
+ }
925
+ /**
926
+ * Find the schema file of a table in schemaDir, or next to the table's JSONL file when unset
927
+ */
928
+ async findTableSchemaFile(tableName, config) {
929
+ return findSchemaFile(this.config.schemaDir ?? dirname(config.jsonlPath), tableName);
930
+ }
931
+ /**
932
+ * Load a single table from JSONL file
933
+ * @returns Object with loaded status and validation errors
934
+ */
935
+ async loadTable(tableName, config, detailedValidate, transform, failedDependencies) {
936
+ let data = [];
937
+ const origins = [];
938
+ const contentHashes = /* @__PURE__ */ new Map();
939
+ for (const jsonlPath of config.jsonlPaths ?? [config.jsonlPath]) {
940
+ const readResult = await JsonlReader.readSnapshot(jsonlPath);
941
+ if (!readResult.ok) throw readResult.error;
942
+ const { rows, contentHash } = readResult.value;
943
+ if (!rows.ok) throw rows.error;
944
+ if (contentHash !== void 0) {
945
+ contentHashes.set(jsonlPath, contentHash);
946
+ this.observedHashes.set(jsonlPath, contentHash);
947
+ }
948
+ rows.value.forEach((row, rowIndex) => {
949
+ data.push(row);
950
+ origins.push({
951
+ file: jsonlPath,
952
+ rowIndex
953
+ });
954
+ });
955
+ }
956
+ const transformedFields = [];
957
+ if (transform) data = data.map((row) => {
958
+ const transformed = transform(row);
959
+ transformedFields.push(Object.keys(transformed).filter((key) => JSON.stringify(transformed[key]) !== JSON.stringify(row[key])));
960
+ return transformed;
961
+ });
962
+ let validationSchema = config.validationSchema;
963
+ const schemaMetadata = {};
964
+ const schemaPath = config.validationSchema ? void 0 : await this.findTableSchemaFile(tableName, config);
965
+ if (!validationSchema && schemaPath) validationSchema = await SchemaLoader.loadSchema(config.jsonlPath, dirname(schemaPath));
966
+ if (!config.validationSchema) try {
967
+ const { pathToFileURL } = await import("node:url");
968
+ if (!schemaPath) throw new Error("Schema file not found");
969
+ const schemaModule = await import(`${pathToFileURL(schemaPath).href}?t=${Date.now()}`);
970
+ const schemaExport = schemaModule.schema || schemaModule.default;
971
+ if (schemaExport?.primaryKey) schemaMetadata.primaryKey = schemaExport.primaryKey;
972
+ else if (schemaModule.primaryKey) schemaMetadata.primaryKey = schemaModule.primaryKey;
973
+ if (schemaExport?.foreignKeys) schemaMetadata.foreignKeys = schemaExport.foreignKeys;
974
+ else if (schemaModule.foreignKeys) schemaMetadata.foreignKeys = schemaModule.foreignKeys;
975
+ if (schemaExport?.indexes) schemaMetadata.indexes = schemaExport.indexes;
976
+ else if (schemaModule.indexes) schemaMetadata.indexes = schemaModule.indexes;
977
+ if (process.env.DEBUG_LINES_DB) {
978
+ console.log(`[lines-db] Schema metadata for ${tableName}:`);
979
+ console.log(` primaryKey: ${schemaMetadata.primaryKey}`);
980
+ console.log(` foreignKeys: ${JSON.stringify(schemaMetadata.foreignKeys)}`);
981
+ console.log(` indexes: ${JSON.stringify(schemaMetadata.indexes)}`);
982
+ }
983
+ } catch (_error) {
984
+ if (process.env.DEBUG_LINES_DB) console.warn(`[lines-db] Failed to load schema metadata for ${tableName}:`, _error instanceof Error ? _error.message : String(_error));
985
+ }
986
+ this.validationSchemas.set(tableName, validationSchema);
987
+ const validationErrors = [];
988
+ const validatedData = [];
989
+ this.keyOrders.delete(tableName);
990
+ for (let rowIndex = 0; rowIndex < data.length; rowIndex++) {
991
+ const row = data[rowIndex];
992
+ try {
993
+ const validatedRow = this.validateAndTransform(tableName, row);
994
+ this.recordKeyOrder(tableName, validatedRow);
995
+ validatedData.push(validatedRow);
996
+ } catch (error) {
997
+ if (error instanceof Error && error.name === "ValidationError") validationErrors.push({
998
+ rowIndex,
999
+ rowData: row,
1000
+ error
1001
+ });
1002
+ else throw error;
1003
+ }
1004
+ }
1005
+ const validationErrorDetails = validationErrors.map((ve) => ({
1006
+ ...origins[ve.rowIndex],
1007
+ tableName,
1008
+ issues: ve.error.issues,
1009
+ type: "schema"
1010
+ }));
1011
+ if (validationErrors.length > 0) return {
1012
+ loaded: false,
1013
+ rowCount: data.length,
1014
+ errors: validationErrorDetails
1015
+ };
1016
+ let schema;
1017
+ let inferredSchema;
1018
+ if (validatedData.length > 0) inferredSchema = unwrap(JsonlReader.inferSchema(tableName, validatedData));
1019
+ if (config.schema) {
1020
+ schema = config.schema;
1021
+ if (inferredSchema) for (const inferredCol of inferredSchema.columns) {
1022
+ const schemaCol = schema.columns.find((c) => c.name === inferredCol.name);
1023
+ if (schemaCol && inferredCol.valueType && !schemaCol.valueType) schemaCol.valueType = inferredCol.valueType;
1024
+ }
1025
+ } else if (config.autoInferSchema !== false) {
1026
+ if (validatedData.length === 0) return {
1027
+ loaded: false,
1028
+ rowCount: 0,
1029
+ errors: []
1030
+ };
1031
+ schema = inferredSchema;
1032
+ } else throw new Error(`No schema provided for table ${tableName} and autoInferSchema is disabled`);
1033
+ const biSchema = validationSchema;
1034
+ const primaryKey = biSchema?.primaryKey || schemaMetadata.primaryKey;
1035
+ const foreignKeys = biSchema?.foreignKeys || schemaMetadata.foreignKeys;
1036
+ const indexes = biSchema?.indexes || schemaMetadata.indexes;
1037
+ if (primaryKey && !schema.columns.some((col) => col.primaryKey)) {
1038
+ const col = schema.columns.find((c) => c.name === primaryKey);
1039
+ if (col) col.primaryKey = true;
1040
+ } else if (!primaryKey && !schema.columns.some((col) => col.primaryKey)) {
1041
+ const idColumn = schema.columns.find((c) => c.name === "id");
1042
+ if (idColumn) idColumn.primaryKey = true;
1043
+ }
1044
+ if (foreignKeys) {
1045
+ schema.declaredForeignKeys = foreignKeys;
1046
+ schema.foreignKeys = failedDependencies && failedDependencies.size > 0 ? foreignKeys.filter((fk) => !failedDependencies.has(fk.references.table)) : foreignKeys;
1047
+ }
1048
+ if (indexes) {
1049
+ schema.indexes = indexes;
1050
+ for (const index of indexes) if (index.unique && index.columns.length === 1) {
1051
+ const col = schema.columns.find((c) => c.name === index.columns[0]);
1052
+ if (col && !col.unique && !col.primaryKey) col.unique = true;
1053
+ }
1054
+ }
1055
+ this.schemas.set(tableName, schema);
1056
+ this.createTable(schema);
1057
+ if (detailedValidate || this.config.writeDataSets) {
1058
+ const insertErrors = this.insertDataWithDetailedValidation(tableName, schema, validatedData, origins);
1059
+ if (insertErrors.length > 0) return {
1060
+ loaded: false,
1061
+ rowCount: data.length,
1062
+ errors: insertErrors
1063
+ };
1064
+ } else this.insertData(tableName, schema, validatedData);
1065
+ this.fieldChanges.delete(tableName);
1066
+ this.linesWithUnknownFields.delete(tableName);
1067
+ const columnNames = new Set(schema.columns.map((column) => column.name));
1068
+ const withUnknown = data.map((row) => Object.keys(row).some((key) => !columnNames.has(key)));
1069
+ if (transformedFields.some((fields) => fields.length > 0) || withUnknown.includes(true)) {
1070
+ const rowids = this.queryInternal(`SELECT rowid AS "${ROWID_ALIAS}" FROM ${this.quoteTableName(tableName)} ORDER BY rowid`);
1071
+ const lines = /* @__PURE__ */ new Map();
1072
+ const sourceIndexes = new Map(origins.map((origin, index) => [origin, index]));
1073
+ rowids.forEach((row, index) => {
1074
+ const rowid = row[ROWID_ALIAS];
1075
+ const origin = this.rowOriginsByRowid.get(tableName)?.get(String(rowid));
1076
+ const sourceIndex = origin ? sourceIndexes.get(origin) ?? index : index;
1077
+ const set = transformedFields[sourceIndex] ?? [];
1078
+ if (set.length > 0) this.noteFieldChanges(tableName, rowid, { set });
1079
+ if (withUnknown[sourceIndex]) lines.set(String(rowid), data[sourceIndex]);
1080
+ });
1081
+ this.linesWithUnknownFields.set(tableName, lines);
1082
+ }
1083
+ for (const [jsonlPath, contentHash] of contentHashes) this.fileHashes.set(jsonlPath, contentHash);
1084
+ return {
1085
+ loaded: true,
1086
+ rowCount: data.length,
1087
+ errors: []
1088
+ };
1089
+ }
1090
+ /**
1091
+ * Create table in SQLite with constraints and indexes
1092
+ */
1093
+ createTable(schema) {
1094
+ const quotedTableName = this.quoteTableName(schema.name);
1095
+ const uniqueColumns = /* @__PURE__ */ new Set();
1096
+ for (const col of schema.columns) if (col.unique) uniqueColumns.add(col.name);
1097
+ if (schema.indexes) {
1098
+ for (const index of schema.indexes) if (index.unique && index.columns.length === 1) uniqueColumns.add(index.columns[0]);
1099
+ }
1100
+ const columnDefs = schema.columns.map((col) => {
1101
+ const sqlType = col.type === "JSON" ? "TEXT" : col.type;
1102
+ const parts = [this.quoteIdentifier(col.name), sqlType];
1103
+ if (col.primaryKey) parts.push("PRIMARY KEY");
1104
+ if (col.notNull) parts.push("NOT NULL");
1105
+ if (uniqueColumns.has(col.name) && !col.primaryKey) parts.push("UNIQUE");
1106
+ return parts.join(" ");
1107
+ });
1108
+ const foreignKeyDefs = [];
1109
+ if (schema.foreignKeys && schema.foreignKeys.length > 0) for (const fk of schema.foreignKeys) {
1110
+ const fkParts = [`FOREIGN KEY (${this.quoteIdentifier(fk.column)})`, `REFERENCES ${this.quoteTableName(fk.references.table)}(${this.quoteIdentifier(fk.references.column)})`];
1111
+ if (fk.onDelete) fkParts.push(`ON DELETE ${fk.onDelete}`);
1112
+ if (fk.onUpdate) fkParts.push(`ON UPDATE ${fk.onUpdate}`);
1113
+ foreignKeyDefs.push(fkParts.join(" "));
1114
+ }
1115
+ const sql = `CREATE TABLE IF NOT EXISTS ${quotedTableName} (${[...columnDefs, ...foreignKeyDefs].join(", ")})`;
1116
+ this.db.exec(sql);
1117
+ if (this.hasSeveralDataDirs() && this.config.writeDataSets) {
1118
+ const moves = this.quoteIdentifier(this.rowMovesTable);
1119
+ const trigger = this.quoteIdentifier(`${this.rowMovesTable}_${schema.name}`);
1120
+ const name = `'${schema.name.replace(/'/g, "''")}'`;
1121
+ this.db.exec(`CREATE TEMP TABLE IF NOT EXISTS ${moves} (tableName TEXT, oldRowid INTEGER, newRowid INTEGER)`);
1122
+ this.db.exec(`CREATE TEMP TRIGGER IF NOT EXISTS ${trigger} AFTER UPDATE ON ${quotedTableName}
1123
+ WHEN OLD.rowid != NEW.rowid BEGIN
1124
+ INSERT INTO ${moves} VALUES (${name}, OLD.rowid, NEW.rowid);
1125
+ END`);
1126
+ }
1127
+ if (schema.indexes && schema.indexes.length > 0) for (let i = 0; i < schema.indexes.length; i++) {
1128
+ const index = schema.indexes[i];
1129
+ const safeTableName = schema.name.replace(/[^a-zA-Z0-9]/g, "_");
1130
+ const resolvedIndexName = index.name || `idx_${safeTableName}_${index.columns.join("_")}_${i}`;
1131
+ const indexSql = `CREATE ${index.unique ? "UNIQUE " : ""}INDEX IF NOT EXISTS ${this.quoteIdentifier(resolvedIndexName)} ON ${quotedTableName} (${index.columns.map((col) => this.quoteIdentifier(col)).join(", ")})`;
1132
+ this.db.exec(indexSql);
1133
+ }
1134
+ }
1135
+ /**
1136
+ * Quote table name to handle special characters in SQL
1137
+ */
1138
+ quoteTableName(tableName) {
1139
+ return this.quoteIdentifier(tableName);
1140
+ }
1141
+ /**
1142
+ * Quote identifier for SQL statements, escaping embedded quotes
1143
+ */
1144
+ quoteIdentifier(identifier) {
1145
+ return `"${identifier.replace(/"/g, "\"\"")}"`;
1146
+ }
1147
+ /**
1148
+ * Insert data into table using batch insert (multiple rows per SQL)
1149
+ * SQLite has a parameter limit (default 999), so we batch rows accordingly
1150
+ * Throws exception if any constraint violation occurs
1151
+ */
1152
+ insertData(tableName, schema, data) {
1153
+ if (data.length === 0) return;
1154
+ const columnNames = schema.columns.map((col) => col.name);
1155
+ const quotedColumns = columnNames.map((name) => this.quoteIdentifier(name));
1156
+ const columnCount = columnNames.length;
1157
+ const maxBatchSize = Math.floor(900 / columnCount);
1158
+ const batchSize = Math.max(1, Math.min(maxBatchSize, 100));
1159
+ for (let i = 0; i < data.length; i += batchSize) {
1160
+ const batch = data.slice(i, i + batchSize);
1161
+ const rowPlaceholders = columnNames.map(() => "?").join(", ");
1162
+ const valuesPlaceholders = batch.map(() => `(${rowPlaceholders})`).join(", ");
1163
+ const sql = `INSERT INTO ${this.quoteTableName(tableName)} (${quotedColumns.join(", ")}) VALUES ${valuesPlaceholders}`;
1164
+ const values = [];
1165
+ for (const row of batch) for (const col of columnNames) values.push(this.normalizeValue(row[col]));
1166
+ this.db.prepare(sql).run(...values);
1167
+ }
1168
+ }
1169
+ /**
1170
+ * Insert data into table one row at a time with detailed error reporting
1171
+ * This is used for validation to catch constraint violations
1172
+ */
1173
+ insertDataWithDetailedValidation(tableName, schema, data, origins) {
1174
+ const errors = [];
1175
+ const columnNames = schema.columns.map((col) => col.name);
1176
+ const quotedColumns = columnNames.map((name) => this.quoteIdentifier(name));
1177
+ const placeholders = columnNames.map(() => "?").join(", ");
1178
+ const sql = `INSERT INTO ${this.quoteTableName(tableName)} (${quotedColumns.join(", ")}) VALUES (${placeholders})`;
1179
+ const stmt = this.db.prepare(sql);
1180
+ const rowOrigins = /* @__PURE__ */ new Map();
1181
+ this.rowOriginsByRowid.set(tableName, rowOrigins);
1182
+ for (let rowIndex = 0; rowIndex < data.length; rowIndex++) {
1183
+ const row = data[rowIndex];
1184
+ try {
1185
+ const values = columnNames.map((col) => this.normalizeValue(row[col]));
1186
+ const { lastInsertRowid } = stmt.run(...values);
1187
+ rowOrigins.set(String(lastInsertRowid), origins[rowIndex]);
1188
+ } catch (error) {
1189
+ const constraintError = this.analyzeConstraintError(error, origins[rowIndex].file, tableName, origins[rowIndex].rowIndex, row, schema.foreignKeys || []);
1190
+ if (constraintError) errors.push(constraintError);
1191
+ }
1192
+ }
1193
+ return errors;
1194
+ }
1195
+ /**
1196
+ * Analyze constraint error and extract detailed information
1197
+ */
1198
+ analyzeConstraintError(error, file, tableName, rowIndex, row, foreignKeys) {
1199
+ const errorMessage = error instanceof Error ? error.message : String(error);
1200
+ if (errorMessage.includes("FOREIGN KEY constraint failed")) for (const fk of foreignKeys) {
1201
+ const fkValue = row[fk.column];
1202
+ if (fkValue === null || fkValue === void 0) continue;
1203
+ try {
1204
+ const result = this.queryInternal(`SELECT COUNT(*) as count FROM ${this.quoteIdentifier(fk.references.table)} WHERE ${this.quoteIdentifier(fk.references.column)} = ?`, [this.normalizeValue(fkValue)]);
1205
+ if (result.length > 0 && result[0].count === 0) return {
1206
+ file,
1207
+ tableName,
1208
+ rowIndex,
1209
+ issues: [],
1210
+ type: "foreignKey",
1211
+ foreignKeyError: {
1212
+ column: fk.column,
1213
+ value: fkValue,
1214
+ referencedTable: fk.references.table,
1215
+ referencedColumn: fk.references.column
1216
+ }
1217
+ };
1218
+ } catch (_) {}
1219
+ }
1220
+ return {
1221
+ file,
1222
+ tableName,
1223
+ rowIndex,
1224
+ issues: [{
1225
+ message: errorMessage,
1226
+ path: []
1227
+ }],
1228
+ type: "schema"
1229
+ };
1230
+ }
1231
+ /**
1232
+ * Validate a deferred foreign key constraint after all tables have been loaded.
1233
+ * Used for circular dependency FK validation.
1234
+ */
1235
+ validateDeferredForeignKey(tableName, fk, filePath) {
1236
+ const errors = [];
1237
+ const quotedTable = this.quoteTableName(tableName);
1238
+ const quotedColumn = this.quoteIdentifier(fk.column);
1239
+ const quotedRefTable = this.quoteTableName(fk.references.table);
1240
+ const sql = `SELECT rowid as rid, ${quotedColumn} as val FROM ${quotedTable} WHERE ${quotedColumn} IS NOT NULL AND ${quotedColumn} NOT IN (SELECT ${this.quoteIdentifier(fk.references.column)} FROM ${quotedRefTable})`;
1241
+ try {
1242
+ const rows = this.queryInternal(sql);
1243
+ const rowOrigins = this.rowOriginsByRowid.get(tableName);
1244
+ for (const row of rows) errors.push({
1245
+ ...rowOrigins?.get(String(row.rid)) ?? {
1246
+ file: filePath,
1247
+ rowIndex: Number(row.rid) - 1
1248
+ },
1249
+ tableName,
1250
+ issues: [],
1251
+ type: "foreignKey",
1252
+ foreignKeyError: {
1253
+ column: fk.column,
1254
+ value: row.val,
1255
+ referencedTable: fk.references.table,
1256
+ referencedColumn: fk.references.column
1257
+ }
1258
+ });
1259
+ } catch (_) {}
1260
+ return errors;
1261
+ }
1262
+ /**
1263
+ * Execute a raw SQL query
1264
+ */
1265
+ query(sql, params = []) {
1266
+ try {
1267
+ this.enforceReadOnlySql();
1268
+ this.refuseUnsafeSql(sql);
1269
+ return ok(this.trackRawSql(() => this.readOnlyWhileTransactionSettles(() => this.queryInternal(sql, params))));
1270
+ } catch (error) {
1271
+ return err(toError(error));
1272
+ }
1273
+ }
1274
+ queryInternal(sql, params = []) {
1275
+ return this.db.prepare(sql).all(...params);
1276
+ }
1277
+ /**
1278
+ * Execute a SQL query that returns a single row
1279
+ */
1280
+ queryOne(sql, params = []) {
1281
+ try {
1282
+ this.enforceReadOnlySql();
1283
+ this.refuseUnsafeSql(sql);
1284
+ return ok(this.trackRawSql(() => this.readOnlyWhileTransactionSettles(() => this.queryOneInternal(sql, params))));
1285
+ } catch (error) {
1286
+ return err(toError(error));
1287
+ }
1288
+ }
1289
+ queryOneInternal(sql, params = []) {
1290
+ const result = this.db.prepare(sql).get(...params);
1291
+ return result === void 0 ? null : result;
1292
+ }
1293
+ /**
1294
+ * Execute a SQL statement (INSERT, UPDATE, DELETE)
1295
+ */
1296
+ execute(sql, params = []) {
1297
+ try {
1298
+ this.enforceReadOnlySql();
1299
+ this.refuseUnsafeSql(sql);
1300
+ this.refuseWhileTransactionSettles("run SQL");
1301
+ return ok(this.trackRawSql(() => this.readOnlyWhileTransactionSettles(() => this.executeInternal(sql, params))));
1302
+ } catch (error) {
1303
+ return err(toError(error));
1304
+ }
1305
+ }
1306
+ /**
1307
+ * Run a caller's SQL, and when it changed rows, write back every table whole: which tables and
1308
+ * fields raw SQL changed is unknown, and a query() can change rows with RETURNING too
1309
+ */
1310
+ trackRawSql(run) {
1311
+ const before = this.totalChanges();
1312
+ try {
1313
+ return run();
1314
+ } finally {
1315
+ if (this.totalChanges() !== before) {
1316
+ for (const tableName of this.schemas.keys()) {
1317
+ this.rawSqlTables.add(tableName);
1318
+ this.noteChange(tableName);
1319
+ }
1320
+ this.forgetLinesOfGoneRows(this.schemas.keys());
1321
+ if (this.transactionChanges) this.transactionChanges = "all";
1322
+ }
1323
+ }
1324
+ }
1325
+ totalChanges() {
1326
+ return Number(this.db.prepare("SELECT total_changes() AS n").get().n);
1327
+ }
1328
+ executeInternal(sql, params = []) {
1329
+ const result = this.db.prepare(sql).run(...params);
1330
+ if (this.hasSeveralDataDirs() && this.config.writeDataSets) {
1331
+ const moves = this.quoteIdentifier(this.rowMovesTable);
1332
+ const changes = this.queryInternal(`SELECT tableName, oldRowid, newRowid FROM ${moves} ORDER BY rowid`);
1333
+ for (const change of changes) this.moveRowMetadata(change.tableName, String(change.oldRowid), String(change.newRowid));
1334
+ if (changes.length > 0) this.db.exec(`DELETE FROM ${moves}`);
1335
+ }
1336
+ return result;
1337
+ }
1338
+ /**
1339
+ * Find rows by condition (supports OR/AND with arrays and function filters)
1340
+ * If where is not provided, returns all rows
1341
+ */
1342
+ find(tableName, where) {
1343
+ try {
1344
+ return ok(this.findInternal(tableName, where));
1345
+ } catch (error) {
1346
+ return err(toError(error));
1347
+ }
1348
+ }
1349
+ findInternal(tableName, where) {
1350
+ if (where === void 0) return this.queryInternal(`SELECT * FROM ${this.quoteTableName(tableName)}`).map((row) => this.deserializeRow(tableName, row));
1351
+ if (Array.isArray(where) && where.length === 0) return [];
1352
+ const { sql, values, functionFilters, hasOrWithFunctionFilters } = this.buildWhereClause(where);
1353
+ let rows;
1354
+ if (hasOrWithFunctionFilters) {
1355
+ rows = this.queryInternal(`SELECT * FROM ${this.quoteTableName(tableName)}`).map((row) => this.deserializeRow(tableName, row));
1356
+ return this.applyOrConditionWithFilters(rows, where);
1357
+ }
1358
+ if (sql) rows = this.queryInternal(`SELECT * FROM ${this.quoteTableName(tableName)} WHERE ${sql}`, values).map((row) => this.deserializeRow(tableName, row));
1359
+ else rows = this.queryInternal(`SELECT * FROM ${this.quoteTableName(tableName)}`).map((row) => this.deserializeRow(tableName, row));
1360
+ return this.applyFunctionFilters(rows, functionFilters);
1361
+ }
1362
+ /**
1363
+ * Find a single row by condition (supports OR/AND with arrays and function filters)
1364
+ */
1365
+ findOne(tableName, where) {
1366
+ try {
1367
+ return ok(this.findOneInternal(tableName, where));
1368
+ } catch (error) {
1369
+ return err(toError(error));
1370
+ }
1371
+ }
1372
+ findOneInternal(tableName, where) {
1373
+ const { sql, values, functionFilters } = this.buildWhereClause(where);
1374
+ let rows;
1375
+ if (sql) rows = this.queryInternal(`SELECT * FROM ${this.quoteTableName(tableName)} WHERE ${sql}`, values).map((row) => this.deserializeRow(tableName, row));
1376
+ else rows = this.queryInternal(`SELECT * FROM ${this.quoteTableName(tableName)}`).map((row) => this.deserializeRow(tableName, row));
1377
+ const filtered = this.applyFunctionFilters(rows, functionFilters);
1378
+ return filtered.length > 0 ? filtered[0] : null;
1379
+ }
1380
+ /**
1381
+ * Deserialize JSON columns in a row
1382
+ */
1383
+ deserializeRow(tableName, row) {
1384
+ const schema = this.schemas.get(tableName);
1385
+ if (!schema) return row;
1386
+ const deserializedRow = { ...row };
1387
+ for (const column of schema.columns) {
1388
+ const colName = column.name;
1389
+ if (!(colName in deserializedRow)) continue;
1390
+ const value = deserializedRow[colName];
1391
+ if (column.type === "JSON" && typeof value === "string") {
1392
+ try {
1393
+ deserializedRow[colName] = JSON.parse(value);
1394
+ } catch (error) {
1395
+ console.warn(`Failed to parse JSON column ${colName}:`, error);
1396
+ }
1397
+ continue;
1398
+ }
1399
+ if (column.valueType === "boolean") {
1400
+ if (typeof value === "number") deserializedRow[colName] = value === 0 ? false : true;
1401
+ else if (typeof value === "bigint") deserializedRow[colName] = value === 0n ? false : true;
1402
+ }
1403
+ }
1404
+ return deserializedRow;
1405
+ }
1406
+ /**
1407
+ * Validate data using StandardSchema and return the transformed value
1408
+ * Note: Only synchronous validation is supported
1409
+ */
1410
+ validateAndTransform(tableName, data) {
1411
+ const schema = this.validationSchemas.get(tableName);
1412
+ if (!schema) return data;
1413
+ const result = schema["~standard"].validate(data);
1414
+ if (result instanceof Promise) throw new Error("Asynchronous validation is not supported. Please use synchronous validation schemas.");
1415
+ if (result.issues && result.issues.length > 0) {
1416
+ const errorMessage = `Validation failed for table '${tableName}':\n${result.issues.map((issue) => {
1417
+ let pathStr = "root";
1418
+ if (issue.path && issue.path.length > 0) pathStr = issue.path.map((segment) => {
1419
+ if (typeof segment === "object" && segment !== null && "key" in segment) return String(segment.key);
1420
+ return String(segment);
1421
+ }).join(".");
1422
+ return ` - ${pathStr}: ${issue.message}`;
1423
+ }).join("\n")}`;
1424
+ const error = new Error(errorMessage);
1425
+ error.name = "ValidationError";
1426
+ error.issues = result.issues;
1427
+ throw error;
1428
+ }
1429
+ const transformedValue = "value" in result ? result.value : data;
1430
+ const normalizedValue = {};
1431
+ for (const [key, value] of Object.entries(transformedValue)) normalizedValue[key] = value === void 0 ? null : value;
1432
+ return normalizedValue;
1433
+ }
1434
+ /**
1435
+ * Validate data using StandardSchema (without returning transformed value)
1436
+ * Note: Only synchronous validation is supported
1437
+ */
1438
+ validateData(tableName, data) {
1439
+ this.validateAndTransform(tableName, data);
1440
+ }
1441
+ /**
1442
+ * Remember the order a computed row lists its fields in - the order the schema declares them, since
1443
+ * that is the order a hook or a validation fills a row in. A sync inserts a key the line did not
1444
+ * have at the place this order gives it.
1445
+ */
1446
+ recordKeyOrder(tableName, row) {
1447
+ const order = this.keyOrders.get(tableName) ?? /* @__PURE__ */ new Set();
1448
+ for (const key of Object.keys(row)) order.add(key);
1449
+ this.keyOrders.set(tableName, order);
1450
+ }
1451
+ /**
1452
+ * Insert a row into a table with validation
1453
+ */
1454
+ insert(tableName, data, options) {
1455
+ try {
1456
+ return ok(this.insertInternal(tableName, data, options));
1457
+ } catch (error) {
1458
+ return err(toError(error));
1459
+ }
1460
+ }
1461
+ insertInternal(tableName, data, options) {
1462
+ this.assertMutable(tableName);
1463
+ let destination;
1464
+ if (this.hasSeveralDataDirs()) {
1465
+ const dataDir = options?.dataDir;
1466
+ if (!dataDir || ![this.config.dataDir].flat().some((dir) => resolve(dir) === resolve(dataDir))) throw new Error("Choose an insert dataDir from the configured data directories");
1467
+ destination = join([this.config.dataDir].flat().find((dir) => resolve(dir) === resolve(dataDir)), `${tableName}.jsonl`);
1468
+ }
1469
+ const row = this.validateAndTransform(tableName, data);
1470
+ if (!this.schemas.get(tableName)) throw new Error(`Table ${tableName} does not exist`);
1471
+ const columnNames = Object.keys(row);
1472
+ const quotedColumns = columnNames.map((col) => this.quoteIdentifier(col));
1473
+ const placeholders = columnNames.map(() => "?").join(", ");
1474
+ const sql = `INSERT INTO ${this.quoteTableName(tableName)} (${quotedColumns.join(", ")}) VALUES (${placeholders})`;
1475
+ const values = Object.values(row).map((v) => this.normalizeValue(v));
1476
+ const result = this.executeInternal(sql, values);
1477
+ if (destination) {
1478
+ const origins = this.rowOriginsByRowid.get(tableName) ?? /* @__PURE__ */ new Map();
1479
+ origins.set(String(result.lastInsertRowid), {
1480
+ file: destination,
1481
+ rowIndex: -1
1482
+ });
1483
+ this.rowOriginsByRowid.set(tableName, origins);
1484
+ }
1485
+ this.noteFieldChanges(tableName, result.lastInsertRowid, {
1486
+ set: givenFields(data),
1487
+ inserted: true
1488
+ });
1489
+ this.afterWrite(tableName, result.changes);
1490
+ return result;
1491
+ }
1492
+ /**
1493
+ * Batch insert rows with validation per record.
1494
+ */
1495
+ batchInsert(tableName, records) {
1496
+ try {
1497
+ return ok(this.batchInsertInternal(tableName, records));
1498
+ } catch (error) {
1499
+ return err(toError(error));
1500
+ }
1501
+ }
1502
+ batchInsertInternal(tableName, records) {
1503
+ this.assertMutable(tableName);
1504
+ if (this.hasSeveralDataDirs()) throw new Error("Use insert with a dataDir for data sets");
1505
+ if (!this.schemas.get(tableName)) throw new Error(`Table ${tableName} does not exist`);
1506
+ if (records.length === 0) return {
1507
+ changes: 0,
1508
+ lastInsertRowid: 0
1509
+ };
1510
+ let totalChanges = 0n;
1511
+ let lastRowid = 0n;
1512
+ try {
1513
+ for (const record of records) {
1514
+ const row = this.validateAndTransform(tableName, record);
1515
+ const columnNames = Object.keys(row);
1516
+ const quotedColumns = columnNames.map((col) => this.quoteIdentifier(col));
1517
+ const placeholders = columnNames.map(() => "?").join(", ");
1518
+ const sql = `INSERT INTO ${this.quoteTableName(tableName)} (${quotedColumns.join(", ")}) VALUES (${placeholders})`;
1519
+ const values = columnNames.map((col) => this.normalizeValue(row[col]));
1520
+ const result = this.executeInternal(sql, values);
1521
+ this.noteFieldChanges(tableName, result.lastInsertRowid, {
1522
+ set: givenFields(record),
1523
+ inserted: true
1524
+ });
1525
+ totalChanges += BigInt(result.changes);
1526
+ lastRowid = BigInt(result.lastInsertRowid);
1527
+ }
1528
+ } finally {
1529
+ this.afterWrite(tableName, totalChanges);
1530
+ }
1531
+ return {
1532
+ changes: totalChanges,
1533
+ lastInsertRowid: lastRowid
1534
+ };
1535
+ }
1536
+ /**
1537
+ * Update rows in a table with validation (supports OR/AND with arrays)
1538
+ * Note: Function filters are not supported for update operations
1539
+ * Note: By default, validation is enabled. For partial updates, existing data is fetched
1540
+ * and merged before validation. Set options.validate = false to disable validation.
1541
+ */
1542
+ update(tableName, data, where, options) {
1543
+ try {
1544
+ return ok(this.updateInternal(tableName, data, where, options));
1545
+ } catch (error) {
1546
+ return err(toError(error));
1547
+ }
1548
+ }
1549
+ updateInternal(tableName, data, where, options) {
1550
+ this.assertMutable(tableName);
1551
+ if (!this.schemas.get(tableName)) throw new Error(`Table ${tableName} does not exist`);
1552
+ const shouldValidate = options?.validate !== false;
1553
+ const hasValidationSchema = this.validationSchemas.has(tableName);
1554
+ if (shouldValidate && hasValidationSchema) {
1555
+ const existingRows = this.findInternal(tableName, where);
1556
+ for (const existingRow of existingRows) {
1557
+ const mergedData = {
1558
+ ...existingRow,
1559
+ ...data
1560
+ };
1561
+ for (const field of options?.resetToDefault ?? []) delete mergedData[field];
1562
+ this.validateData(tableName, mergedData);
1563
+ }
1564
+ }
1565
+ const { sql: whereSql, values: whereValues, functionFilters } = this.buildWhereClause(where);
1566
+ if (functionFilters.length > 0) throw new Error("Function filters are not supported in update operations");
1567
+ const targets = this.queryInternal(`SELECT rowid AS "${ROWID_ALIAS}", * FROM ${this.quoteTableName(tableName)} WHERE ${whereSql}`, whereValues);
1568
+ const resetFields = options?.resetToDefault ?? [];
1569
+ const resets = resetFields.length > 0 ? this.computeResets(tableName, targets, data, resetFields) : [];
1570
+ let result = {
1571
+ changes: 0,
1572
+ lastInsertRowid: 0
1573
+ };
1574
+ if (Object.keys(data).length > 0) {
1575
+ const setClauses = Object.keys(data).map((key) => `${this.quoteIdentifier(key)} = ?`).join(", ");
1576
+ const sql = `UPDATE ${this.quoteTableName(tableName)} SET ${setClauses} WHERE ${whereSql}`;
1577
+ const values = [...Object.values(data).map((v) => this.normalizeValue(v)), ...whereValues];
1578
+ result = this.executeInternal(sql, values);
1579
+ }
1580
+ const pkName = this.schemas.get(tableName)?.columns.find((col) => col.primaryKey)?.name;
1581
+ if (pkName && Object.hasOwn(data, pkName)) {
1582
+ const moved = this.queryInternal(`SELECT rowid AS "${ROWID_ALIAS}" FROM ${this.quoteTableName(tableName)} WHERE ${this.quoteIdentifier(pkName)} = ?`, [this.normalizeValue(data[pkName])]);
1583
+ if (targets.length === 1 && moved.length === 1) {
1584
+ const from = String(targets[0][ROWID_ALIAS]);
1585
+ const to = moved[0][ROWID_ALIAS];
1586
+ if (from !== String(to)) {
1587
+ this.moveRowMetadata(tableName, from, String(to));
1588
+ targets[0] = {
1589
+ ...targets[0],
1590
+ [ROWID_ALIAS]: to
1591
+ };
1592
+ }
1593
+ }
1594
+ }
1595
+ for (const target of targets) {
1596
+ const set = Object.keys(data).filter((key) => !sameStoredValue(target[key], this.normalizeValue(data[key])));
1597
+ this.noteFieldChanges(tableName, target[ROWID_ALIAS], { set });
1598
+ }
1599
+ if (resets.length > 0) result = this.applyResets(tableName, resets, resetFields);
1600
+ this.afterWrite(tableName, result.changes);
1601
+ return result;
1602
+ }
1603
+ /**
1604
+ * Batch update rows with record-specific values and validation.
1605
+ * Each record must include the primary key to identify the target row.
1606
+ * Validation runs once per merged record unless explicitly disabled.
1607
+ */
1608
+ batchUpdate(tableName, records, options) {
1609
+ try {
1610
+ return ok(this.batchUpdateInternal(tableName, records, options));
1611
+ } catch (error) {
1612
+ return err(toError(error));
1613
+ }
1614
+ }
1615
+ batchUpdateInternal(tableName, records, options) {
1616
+ this.assertMutable(tableName);
1617
+ const schema = this.schemas.get(tableName);
1618
+ if (!schema) throw new Error(`Table ${tableName} does not exist`);
1619
+ if (records.length === 0) return {
1620
+ changes: 0,
1621
+ lastInsertRowid: 0
1622
+ };
1623
+ const pkColumn = schema.columns.find((col) => col.primaryKey);
1624
+ if (!pkColumn) throw new Error(`Table ${tableName} does not have a primary key`);
1625
+ const pkName = pkColumn.name;
1626
+ const pkValues = [];
1627
+ for (const record of records) {
1628
+ const pkValue = record[pkName];
1629
+ if (pkValue === void 0) throw new Error(`Record is missing primary key '${String(pkName)}': ${JSON.stringify(record)}`);
1630
+ pkValues.push(pkValue);
1631
+ }
1632
+ const shouldValidate = options?.validate !== false;
1633
+ const hasValidationSchema = this.validationSchemas.has(tableName);
1634
+ if (shouldValidate && hasValidationSchema) {
1635
+ const orCondition = pkValues.map((pkValue) => ({ [pkName]: pkValue }));
1636
+ const existingRows = this.findInternal(tableName, orCondition);
1637
+ const existingRowsMap = /* @__PURE__ */ new Map();
1638
+ for (const row of existingRows) {
1639
+ const pkValue = row[pkName];
1640
+ existingRowsMap.set(pkValue, row);
1641
+ }
1642
+ const validationErrors = [];
1643
+ for (let i = 0; i < records.length; i++) {
1644
+ const record = records[i];
1645
+ const pkValue = record[pkName];
1646
+ const existingRow = existingRowsMap.get(pkValue);
1647
+ if (!existingRow) throw new Error(`No existing row found with ${String(pkName)}=${JSON.stringify(pkValue)}`);
1648
+ const mergedData = {
1649
+ ...existingRow,
1650
+ ...record
1651
+ };
1652
+ try {
1653
+ this.validateData(tableName, mergedData);
1654
+ } catch (error) {
1655
+ if (error instanceof Error && error.name === "ValidationError") validationErrors.push({
1656
+ rowIndex: i,
1657
+ rowData: mergedData,
1658
+ pkValue,
1659
+ error
1660
+ });
1661
+ else throw error;
1662
+ }
1663
+ }
1664
+ if (validationErrors.length > 0) {
1665
+ const enhancedError = /* @__PURE__ */ new Error(`Validation failed for ${validationErrors.length} row(s)`);
1666
+ enhancedError.name = "ValidationError";
1667
+ enhancedError.validationErrors = validationErrors;
1668
+ enhancedError.issues = validationErrors[0].error.issues;
1669
+ throw enhancedError;
1670
+ }
1671
+ }
1672
+ let totalChanges = 0n;
1673
+ let lastRowid = 0n;
1674
+ for (const record of records) {
1675
+ const pkValue = record[pkName];
1676
+ const where = { [pkName]: pkValue };
1677
+ const result = this.updateInternal(tableName, record, where, { validate: false });
1678
+ totalChanges += BigInt(result.changes);
1679
+ lastRowid = BigInt(result.lastInsertRowid);
1680
+ }
1681
+ return {
1682
+ changes: totalChanges,
1683
+ lastInsertRowid: lastRowid
1684
+ };
1685
+ }
1686
+ /**
1687
+ * Delete rows from a table (supports OR/AND with arrays)
1688
+ * Note: Function filters are not supported for delete operations
1689
+ */
1690
+ delete(tableName, where) {
1691
+ try {
1692
+ return ok(this.deleteInternal(tableName, where));
1693
+ } catch (error) {
1694
+ return err(toError(error));
1695
+ }
1696
+ }
1697
+ deleteInternal(tableName, where) {
1698
+ this.assertMutable(tableName);
1699
+ if (!this.schemas.get(tableName)) throw new Error(`Table ${tableName} does not exist`);
1700
+ const { sql: whereSql, values, functionFilters } = this.buildWhereClause(where);
1701
+ if (functionFilters.length > 0) throw new Error("Function filters are not supported in delete operations");
1702
+ const deleted = this.rowidsWhere(tableName, whereSql, values);
1703
+ const sql = `DELETE FROM ${this.quoteTableName(tableName)} WHERE ${whereSql}`;
1704
+ const result = this.executeInternal(sql, values);
1705
+ this.forgetFieldChanges(tableName, deleted);
1706
+ this.afterWrite(tableName, result.changes);
1707
+ return result;
1708
+ }
1709
+ /**
1710
+ * Batch delete rows by primary key.
1711
+ */
1712
+ batchDelete(tableName, records) {
1713
+ try {
1714
+ return ok(this.batchDeleteInternal(tableName, records));
1715
+ } catch (error) {
1716
+ return err(toError(error));
1717
+ }
1718
+ }
1719
+ batchDeleteInternal(tableName, records) {
1720
+ this.assertMutable(tableName);
1721
+ const schema = this.schemas.get(tableName);
1722
+ if (!schema) throw new Error(`Table ${tableName} does not exist`);
1723
+ if (records.length === 0) return {
1724
+ changes: 0,
1725
+ lastInsertRowid: 0
1726
+ };
1727
+ const pkColumn = schema.columns.find((col) => col.primaryKey);
1728
+ if (!pkColumn) throw new Error(`Table ${tableName} does not have a primary key`);
1729
+ const pkName = pkColumn.name;
1730
+ const pkValues = records.map((record, index) => {
1731
+ const pkValue = record[pkName];
1732
+ if (pkValue === void 0) throw new Error(`Record at index ${index} is missing primary key '${String(pkName)}'`);
1733
+ return pkValue;
1734
+ });
1735
+ const placeholders = pkValues.map(() => "?").join(", ");
1736
+ const sql = `DELETE FROM ${this.quoteTableName(tableName)} WHERE ${this.quoteIdentifier(pkName)} IN (${placeholders})`;
1737
+ const values = pkValues.map((value) => this.normalizeValue(value));
1738
+ const deleted = this.rowidsWhere(tableName, `${this.quoteIdentifier(pkName)} IN (${placeholders})`, values);
1739
+ const result = this.executeInternal(sql, values);
1740
+ this.forgetFieldChanges(tableName, deleted);
1741
+ this.afterWrite(tableName, result.changes);
1742
+ return {
1743
+ changes: BigInt(result.changes),
1744
+ lastInsertRowid: BigInt(result.lastInsertRowid)
1745
+ };
1746
+ }
1747
+ /**
1748
+ * Normalize value for SQLite
1749
+ */
1750
+ normalizeValue(value) {
1751
+ if (value === null || value === void 0) return null;
1752
+ if (typeof value === "boolean") return value ? 1 : 0;
1753
+ if (typeof value === "string" || typeof value === "number" || typeof value === "bigint") return value;
1754
+ if (value instanceof Uint8Array) return value;
1755
+ return JSON.stringify(value);
1756
+ }
1757
+ /**
1758
+ * Build WHERE clause from condition (supports OR/AND with arrays and functions)
1759
+ */
1760
+ buildWhereClause(condition) {
1761
+ const values = [];
1762
+ const functionFilters = [];
1763
+ let hasOrWithFunctionFilters = false;
1764
+ const buildCondition = (cond, isInOr = false) => {
1765
+ if (Array.isArray(cond)) return cond.map((item) => {
1766
+ const clause = Array.isArray(item) ? buildCondition(item, true) : buildCondition(item, true);
1767
+ return clause ? `(${clause})` : "";
1768
+ }).filter((clause) => clause !== "").join(" OR ");
1769
+ const conditions = [];
1770
+ let hasFunctionFilter = false;
1771
+ for (const [key, value] of Object.entries(cond)) if (typeof value === "function") {
1772
+ functionFilters.push({
1773
+ key,
1774
+ fn: value
1775
+ });
1776
+ hasFunctionFilter = true;
1777
+ } else {
1778
+ conditions.push(`${this.quoteIdentifier(key)} = ?`);
1779
+ values.push(this.normalizeValue(value));
1780
+ }
1781
+ if (isInOr && hasFunctionFilter) hasOrWithFunctionFilters = true;
1782
+ return conditions.join(" AND ");
1783
+ };
1784
+ return {
1785
+ sql: buildCondition(condition),
1786
+ values,
1787
+ functionFilters,
1788
+ hasOrWithFunctionFilters
1789
+ };
1790
+ }
1791
+ /**
1792
+ * Apply OR condition with function filters by evaluating each row against the condition
1793
+ */
1794
+ applyOrConditionWithFilters(rows, condition) {
1795
+ return rows.filter((row) => this.matchesOrCondition(row, condition));
1796
+ }
1797
+ /**
1798
+ * Check if a row matches an OR/AND condition (recursively)
1799
+ */
1800
+ matchesOrCondition(row, condition) {
1801
+ if (Array.isArray(condition)) return condition.some((item) => this.matchesOrCondition(row, item));
1802
+ return Object.entries(condition).every(([key, value]) => {
1803
+ const rowValue = row[key];
1804
+ if (typeof value === "function") return value(rowValue);
1805
+ return rowValue === value;
1806
+ });
1807
+ }
1808
+ /**
1809
+ * Apply function filters to rows
1810
+ */
1811
+ applyFunctionFilters(rows, functionFilters) {
1812
+ if (functionFilters.length === 0) return rows;
1813
+ return rows.filter((row) => {
1814
+ return functionFilters.every(({ key, fn }) => {
1815
+ const value = row[key];
1816
+ return fn(value);
1817
+ });
1818
+ });
1819
+ }
1820
+ /**
1821
+ * Get table schema
1822
+ */
1823
+ /**
1824
+ * Validate a row against a table's schema, also for a table left out on load because rows failed
1825
+ * validation, so a fix can be checked before it is written to the file
1826
+ */
1827
+ validateRow(tableName, row) {
1828
+ if (!this.tables.has(tableName) && !this.validationSchemas.has(tableName)) {
1829
+ const error = /* @__PURE__ */ new Error(`Table '${tableName}' does not exist`);
1830
+ error.name = "ValidationError";
1831
+ error.issues = [{ message: `Table '${tableName}' does not exist` }];
1832
+ return err(error);
1833
+ }
1834
+ try {
1835
+ return ok(this.validateAndTransform(tableName, row));
1836
+ } catch (error) {
1837
+ if (error instanceof Error && error.name === "ValidationError") return err(error);
1838
+ throw error;
1839
+ }
1840
+ }
1841
+ getSchema(tableName) {
1842
+ return this.schemas.get(tableName);
1843
+ }
1844
+ /**
1845
+ * Get all table names
1846
+ */
1847
+ getTableNames() {
1848
+ return Array.from(this.schemas.keys());
1849
+ }
1850
+ /**
1851
+ * A database composed from several data directories is read-only: the rows of its tables have no
1852
+ * single file to be written back to
1853
+ */
1854
+ hasSeveralDataDirs() {
1855
+ return typeof this.config.dataDir !== "string" && this.config.dataDir.length > 1;
1856
+ }
1857
+ /**
1858
+ * Turn query_only back on before running a caller's SQL, since an earlier call may have run
1859
+ * `PRAGMA query_only = OFF`
1860
+ */
1861
+ /**
1862
+ * Refuse SQL that would end a transaction() or lift the read-only mode that holds back writes made
1863
+ * through the database while it runs. Looked for in each statement as SQLite reads it, so a `;` or a
1864
+ * comment cannot hide one
1865
+ */
1866
+ refuseUnsafeSql(sql, viaTransaction = this.viaTransactionObject) {
1867
+ if (this.hasSeveralDataDirs() && this.config.writeDataSets && splitStatements(sql).some((statement) => !isReadOnlyStatement(statement))) throw new Error("Raw SQL is read-only for composed data sets; use insert, update, or delete to preserve source routing");
1868
+ if (!this.inTransaction && !this.transactionStarting && !this.transactionClosing) return;
1869
+ for (const statement of splitStatements(sql)) {
1870
+ if (this.inTransaction && !viaTransaction && !isReadOnlyStatement(statement)) throw new Error(`'${sql.trim()}' is not a read: while a transaction runs, SQL that changes anything must go through the callback's tx`);
1871
+ if (/^(BEGIN|COMMIT|END|ROLLBACK(?!\s+(TRANSACTION\s+)?TO\b))\b/i.test(statement)) throw new Error(`'${sql.trim()}' would end the transaction before its files are written back; return from the callback to commit, or throw to roll back`);
1872
+ if (!this.inTransaction && /^SAVEPOINT\b/i.test(statement)) throw new Error(`'${sql.trim()}' would open a transaction of its own while the transaction starts`);
1873
+ if (/^PRAGMA\s+(?:(?:\w+|"[^"]*"|'[^']*'|`[^`]*`|\[[^\]]*\])\s*\.\s*)?(?:query_only|"query_only"|'query_only'|`query_only`|\[query_only\])\s*[=(]/i.test(statement)) throw new Error(`'${sql.trim()}' would lift the read-only mode that refuses writes made while a transaction runs`);
1874
+ }
1875
+ }
1876
+ isReadOnlyDataSet() {
1877
+ return this.hasSeveralDataDirs() && !this.config.writeDataSets;
1878
+ }
1879
+ enforceReadOnlySql() {
1880
+ if (this.isReadOnlyDataSet()) this.db.exec("PRAGMA query_only = ON");
1881
+ }
1882
+ /** Writable, and not while a transaction writes back the rows it has already read */
1883
+ assertMutable(tableName) {
1884
+ this.assertWritable(tableName);
1885
+ this.refuseWhileTransactionSettles(`write to table '${tableName}'`);
1886
+ }
1887
+ /**
1888
+ * Refuse a change while a transaction starts or writes its files back: one made while it starts would
1889
+ * be written back with rows the transaction may roll back, and one made while it closes would be
1890
+ * committed without reaching the files. Also refuse one made through the database itself while the
1891
+ * callback runs, which would be committed or rolled back with the transaction unnoticed by its caller
1892
+ */
1893
+ refuseWhileTransactionSettles(action, viaTransaction = this.viaTransactionObject) {
1894
+ if (this.inTransaction && !viaTransaction) throw new Error(`Cannot ${action} through the database while a transaction is running: a change made now would be committed or rolled back with it; use the object the transaction callback receives, or wait until it has finished`);
1895
+ if (this.transactionStarting) throw new Error(`Cannot ${action} while a transaction is starting; ${action.split(" ")[0]} once it has finished`);
1896
+ if (this.transactionClosing) throw new Error(`Cannot ${action} while a transaction writes its files back; ${action.split(" ")[0]} once it has finished`);
1897
+ }
1898
+ /**
1899
+ * Run a query() with the database read-only while a transaction starts or writes its files back.
1900
+ * Not refused outright as execute() is: a query that only reads changes nothing the files would miss
1901
+ */
1902
+ readOnlyWhileTransactionSettles(run, viaTransaction = this.viaTransactionObject) {
1903
+ if (!this.hasSeveralDataDirs() && !this.transactionStarting && !this.transactionClosing && !(this.inTransaction && !viaTransaction)) return run();
1904
+ this.db.exec("PRAGMA query_only = ON");
1905
+ try {
1906
+ return run();
1907
+ } catch (error) {
1908
+ if (/readonly/i.test(toError(error).message)) this.refuseWhileTransactionSettles("change rows", viaTransaction);
1909
+ throw error;
1910
+ } finally {
1911
+ if (!this.isReadOnlyDataSet()) this.db.exec("PRAGMA query_only = OFF");
1912
+ }
1913
+ }
1914
+ assertWritable(tableName) {
1915
+ if (this.isReadOnlyDataSet()) {
1916
+ const target = tableName ? `table '${tableName}'` : "the database";
1917
+ throw new Error(`Cannot write to ${target}: dataDir lists several directories, so its rows have no single file to be written back to`);
1918
+ }
1919
+ }
1920
+ /**
1921
+ * Sync a specific table back to its JSONL file
1922
+ * Syncs of the same table run one after another: auto-sync is fire-and-forget, and a write-back
1923
+ * that reads the file first must never see a file another sync is halfway through writing.
1924
+ */
1925
+ async syncTable(tableName, options) {
1926
+ const current = (this.syncQueue.get(tableName) ?? Promise.resolve()).then(() => this.writeTable(tableName, options));
1927
+ this.syncQueue.set(tableName, current.catch(() => {}));
1928
+ return current;
1929
+ }
1930
+ /**
1931
+ * Write a table back to its JSONL file
1932
+ * Uses backward transformation when available
1933
+ */
1934
+ async writeTable(tableName, options) {
1935
+ await this.writeFilesTogether(await this.prepareWriteBack(tableName, options));
1936
+ }
1937
+ /**
1938
+ * The rows a table is written back as, laid over the lines of its file; fails when the file changed
1939
+ * since this database last read or wrote it
1940
+ */
1941
+ async prepareWriteBack(tableName, options) {
1942
+ this.assertWritable(tableName);
1943
+ const config = this.tables.get(tableName);
1944
+ if (!config) throw new Error(`Table ${tableName} not found`);
1945
+ const stored = this.readStoredRows(tableName);
1946
+ if (!this.hasSeveralDataDirs()) return [await this.prepareFileWriteBack(tableName, config.jsonlPath, stored, options)];
1947
+ const origins = this.rowOriginsByRowid.get(tableName);
1948
+ const byFile = new Map([this.config.dataDir].flat().map((dir) => [join(dir, `${tableName}.jsonl`), []]));
1949
+ stored.rowids.forEach((rowid, index) => {
1950
+ const origin = origins?.get(rowid);
1951
+ if (!origin) throw new Error(`Row ${rowid} of '${tableName}' has no data directory; insert with a dataDir`);
1952
+ const indexes = byFile.get(origin.file) ?? [];
1953
+ indexes.push(index);
1954
+ byFile.set(origin.file, indexes);
1955
+ });
1956
+ const prepared = [];
1957
+ for (const [file, indexes] of byFile) {
1958
+ indexes.sort((a, b) => (origins.get(stored.rowids[a]).rowIndex < 0 ? Infinity : origins.get(stored.rowids[a]).rowIndex) - (origins.get(stored.rowids[b]).rowIndex < 0 ? Infinity : origins.get(stored.rowids[b]).rowIndex));
1959
+ const rows = {
1960
+ rowids: indexes.map((i) => stored.rowids[i]),
1961
+ rows: indexes.map((i) => stored.rows[i]),
1962
+ lineRows: indexes.map((i) => stored.lineRows[i])
1963
+ };
1964
+ const fileWrite = await this.prepareFileWriteBack(tableName, file, rows, options);
1965
+ if (!fileWrite.unchanged) prepared.push(fileWrite);
1966
+ }
1967
+ return prepared;
1968
+ }
1969
+ async prepareFileWriteBack(tableName, jsonlPath, stored, options) {
1970
+ const { rowids, rows: deserializedRows, lineRows } = stored;
1971
+ const generation = this.changeGenerations.get(tableName) ?? 0;
1972
+ let finalRows = lineRows;
1973
+ const previousContent = await readFile(jsonlPath, "utf-8").catch((error) => {
1974
+ if (error.code === "ENOENT") return void 0;
1975
+ throw error;
1976
+ });
1977
+ const existingRows = await this.readUnchangedRows(jsonlPath);
1978
+ const matches = this.hasSeveralDataDirs() ? rowids.map((rowid) => existingRows[this.rowOriginsByRowid.get(tableName).get(rowid).rowIndex]) : void 0;
1979
+ const fields = options?.fields ?? this.config.writeBackFields;
1980
+ if ((options?.writeFilledValues ?? this.config.writeFilledValues ?? "all") === "primaryKey") finalRows = this.keepWrittenFields(tableName, rowids, deserializedRows, finalRows, existingRows, fields, matches).map(({ written }) => written);
1981
+ const columns = new Set(this.schemas.get(tableName)?.columns.map((column) => column.name));
1982
+ const readLines = this.linesWithUnknownFields.get(tableName);
1983
+ finalRows = finalRows.map((row, index) => {
1984
+ const line = readLines?.get(rowids[index]);
1985
+ return line ? keepUnknownFields(line, row, columns) : row;
1986
+ });
1987
+ finalRows = this.mergeWithExistingLines(tableName, existingRows, finalRows, {
1988
+ fields,
1989
+ strictFields: options?.strictFields ?? false,
1990
+ matches
1991
+ });
1992
+ return {
1993
+ tableName,
1994
+ jsonlPath,
1995
+ rows: finalRows,
1996
+ previousContent,
1997
+ generation,
1998
+ ...matches ? {
1999
+ rowids,
2000
+ unchanged: JsonlWriter.serialize(existingRows) === JsonlWriter.serialize(finalRows)
2001
+ } : {}
2002
+ };
2003
+ }
2004
+ /**
2005
+ * Every row of a table in rowid order - the order the file was read in - as stored and as its line
2006
+ * would hold it, after the backward transformation
2007
+ */
2008
+ readStoredRows(tableName) {
2009
+ const stored = this.queryInternal(`SELECT rowid AS "${ROWID_ALIAS}", * FROM ${this.quoteTableName(tableName)} ORDER BY rowid`);
2010
+ const rowids = stored.map((row) => String(row[ROWID_ALIAS]));
2011
+ const rows = stored.map(({ [ROWID_ALIAS]: _rowid, ...row }) => this.deserializeRow(tableName, row));
2012
+ const validationSchema = this.validationSchemas.get(tableName);
2013
+ return {
2014
+ rowids,
2015
+ rows,
2016
+ lineRows: validationSchema && hasBackward(validationSchema) ? rows.map((row) => validationSchema.backward(row)) : rows
2017
+ };
2018
+ }
2019
+ /**
2020
+ * Narrow each row to the fields a user wrote - the ones its line holds, plus those set since and
2021
+ * minus those reset to their default - its primary key and the fields named to be written back, so
2022
+ * a value the schema fills in stays out of the file
2023
+ */
2024
+ keepWrittenFields(tableName, rowids, rows, lineRows, existingRows, namedFields = [], matchedLines) {
2025
+ const pkName = this.schemas.get(tableName)?.columns.find((col) => col.primaryKey)?.name;
2026
+ const actionColumns = (this.schemas.get(tableName)?.foreignKeys ?? []).filter((fk) => [fk.onDelete, fk.onUpdate].some((action) => action === "CASCADE" || action === "SET NULL")).map((fk) => fk.column);
2027
+ const lines = matchedLines ?? this.matchExistingRows(tableName, lineRows, existingRows, { required: false });
2028
+ const changes = this.fieldChanges.get(tableName);
2029
+ return lineRows.map((lineRow, index) => {
2030
+ const line = lines?.[index];
2031
+ const rowChanges = changes?.get(rowids[index]);
2032
+ if (Object.keys(lineRow).some((key) => !Object.hasOwn(rows[index], key)) || this.rawSqlTables.has(tableName) || !line && !rowChanges?.inserted) return {
2033
+ written: lineRow,
2034
+ narrowed: false
2035
+ };
2036
+ const keep = /* @__PURE__ */ new Set([
2037
+ ...Object.keys(line ?? {}),
2038
+ ...rowChanges?.set ?? [],
2039
+ ...actionColumns
2040
+ ]);
2041
+ for (const key of rowChanges?.reset ?? []) keep.delete(key);
2042
+ for (const key of namedFields) keep.add(key);
2043
+ if (pkName) keep.add(pkName);
2044
+ return {
2045
+ written: Object.fromEntries(Object.entries(lineRow).filter(([key]) => keep.has(key))),
2046
+ narrowed: true
2047
+ };
2048
+ });
2049
+ }
2050
+ rowidsWhere(tableName, whereSql, values) {
2051
+ return this.queryInternal(`SELECT rowid AS "${ROWID_ALIAS}" FROM ${this.quoteTableName(tableName)} WHERE ${whereSql}`, values).map((row) => String(row[ROWID_ALIAS]));
2052
+ }
2053
+ /**
2054
+ * Forget the field changes of deleted rows: a deleted row's rowid can be given to a row inserted
2055
+ * later, which must not inherit them
2056
+ */
2057
+ moveRowMetadata(tableName, from, to) {
2058
+ for (const byRow of [
2059
+ this.fieldChanges.get(tableName),
2060
+ this.linesWithUnknownFields.get(tableName),
2061
+ this.rowOriginsByRowid.get(tableName)
2062
+ ]) {
2063
+ const kept = byRow?.get(from);
2064
+ if (!byRow || kept === void 0) continue;
2065
+ byRow.delete(from);
2066
+ byRow.set(to, kept);
2067
+ }
2068
+ }
2069
+ /** Forget the lines kept for rows that are gone, such as rows raw SQL or a foreign-key action deleted */
2070
+ forgetLinesOfGoneRows(tableNames) {
2071
+ for (const tableName of tableNames) {
2072
+ const lines = this.linesWithUnknownFields.get(tableName);
2073
+ if (!lines || lines.size === 0) continue;
2074
+ let stored;
2075
+ try {
2076
+ stored = this.queryInternal(`SELECT rowid AS "${ROWID_ALIAS}" FROM ${this.quoteTableName(tableName)}`);
2077
+ } catch {
2078
+ continue;
2079
+ }
2080
+ const present = new Set(stored.map((row) => String(row[ROWID_ALIAS])));
2081
+ for (const rowid of lines.keys()) if (!present.has(rowid)) lines.delete(rowid);
2082
+ }
2083
+ }
2084
+ forgetFieldChanges(tableName, rowids) {
2085
+ for (const rowid of rowids) {
2086
+ this.fieldChanges.get(tableName)?.delete(rowid);
2087
+ this.linesWithUnknownFields.get(tableName)?.delete(rowid);
2088
+ }
2089
+ }
2090
+ noteChange(tableName) {
2091
+ this.changeGenerations.set(tableName, (this.changeGenerations.get(tableName) ?? 0) + 1);
2092
+ }
2093
+ noteFieldChanges(tableName, rowid, changes) {
2094
+ this.noteChange(tableName);
2095
+ const byRow = this.fieldChanges.get(tableName) ?? /* @__PURE__ */ new Map();
2096
+ const rowChanges = byRow.get(String(rowid)) ?? {
2097
+ set: /* @__PURE__ */ new Set(),
2098
+ reset: /* @__PURE__ */ new Set(),
2099
+ inserted: false
2100
+ };
2101
+ if (changes.inserted) rowChanges.inserted = true;
2102
+ for (const key of changes.set ?? []) {
2103
+ rowChanges.set.add(key);
2104
+ rowChanges.reset.delete(key);
2105
+ }
2106
+ for (const key of changes.reset ?? []) {
2107
+ rowChanges.reset.add(key);
2108
+ rowChanges.set.delete(key);
2109
+ }
2110
+ byRow.set(String(rowid), rowChanges);
2111
+ this.fieldChanges.set(tableName, byRow);
2112
+ }
2113
+ /**
2114
+ * Store the value the schema fills in for each reset field, as validating the row without the field
2115
+ * gives it, and remember the field as reset so it leaves the line
2116
+ */
2117
+ /** The value the schema fills in for each reset field of each target, validating the row without them */
2118
+ computeResets(tableName, targets, data, fields) {
2119
+ return targets.map((target) => {
2120
+ const { [ROWID_ALIAS]: rowid, ...stored } = target;
2121
+ const row = {
2122
+ ...this.deserializeRow(tableName, stored),
2123
+ ...data
2124
+ };
2125
+ for (const field of fields) delete row[field];
2126
+ const validated = this.validateAndTransform(tableName, row);
2127
+ return {
2128
+ rowid,
2129
+ values: fields.map((field) => this.normalizeValue(validated[field]))
2130
+ };
2131
+ });
2132
+ }
2133
+ /** Store the values computeResets gave, and remember the fields as reset so they leave the line */
2134
+ applyResets(tableName, resets, fields) {
2135
+ let changes = 0n;
2136
+ const setClauses = fields.map((field) => `${this.quoteIdentifier(field)} = ?`).join(", ");
2137
+ for (const { rowid, values } of resets) {
2138
+ const result = this.executeInternal(`UPDATE ${this.quoteTableName(tableName)} SET ${setClauses} WHERE rowid = ?`, [...values, rowid]);
2139
+ changes += BigInt(result.changes);
2140
+ this.noteFieldChanges(tableName, rowid, { reset: fields });
2141
+ }
2142
+ return {
2143
+ changes,
2144
+ lastInsertRowid: 0
2145
+ };
2146
+ }
2147
+ /**
2148
+ * Every row of a table with the fields the schema filled in rather than the file: the ones its line
2149
+ * does not hold and no write set, which a write-back leaves out of the file
2150
+ */
2151
+ async findWithDefaults(tableName) {
2152
+ try {
2153
+ const tableConfig = this.tables.get(tableName);
2154
+ if (!tableConfig || !this.schemas.has(tableName)) throw new Error(`Table '${tableName}' is not loaded`);
2155
+ await this.waitForPendingSyncs();
2156
+ const { rowids, rows, lineRows } = this.readStoredRows(tableName);
2157
+ const fileRows = /* @__PURE__ */ new Map();
2158
+ for (const file of this.hasSeveralDataDirs() ? /* @__PURE__ */ new Set([...tableConfig.jsonlPaths ?? [tableConfig.jsonlPath], ...[...this.rowOriginsByRowid.get(tableName)?.values() ?? []].map((origin) => origin.file)]) : [tableConfig.jsonlPath]) fileRows.set(file, await this.readUnchangedRows(file));
2159
+ const existingRows = [...fileRows.values()].flat();
2160
+ const matches = this.hasSeveralDataDirs() && this.config.writeDataSets ? rowids.map((rowid) => {
2161
+ const origin = this.rowOriginsByRowid.get(tableName)?.get(rowid);
2162
+ return origin && fileRows.get(origin.file)?.[origin.rowIndex];
2163
+ }) : void 0;
2164
+ const kept = this.keepWrittenFields(tableName, rowids, rows, lineRows, existingRows, this.config.writeBackFields, matches);
2165
+ return ok(rows.map((row, index) => ({
2166
+ row,
2167
+ defaulted: kept[index].narrowed ? Object.keys(row).filter((key) => !Object.hasOwn(kept[index].written, key)) : []
2168
+ })));
2169
+ } catch (error) {
2170
+ return err(toError(error));
2171
+ }
2172
+ }
2173
+ async writePrepared(prepared) {
2174
+ const { jsonlPath, rows, previousContent } = prepared;
2175
+ if (this.hasSeveralDataDirs() || this.config.writeDataSets) await replaceFile(jsonlPath, (temporary) => JsonlWriter.write(temporary, rows), previousContent);
2176
+ else await JsonlWriter.write(jsonlPath, rows);
2177
+ prepared.completed = true;
2178
+ const contentHash = hashJsonlContent(JsonlWriter.serialize(rows));
2179
+ this.fileHashes.set(jsonlPath, contentHash);
2180
+ this.observedHashes.set(jsonlPath, contentHash);
2181
+ }
2182
+ /**
2183
+ * Write a table back to its file, or leave it to the running transaction, which writes back the
2184
+ * tables it changed once its callback is done
2185
+ */
2186
+ afterWrite(tableName, changes) {
2187
+ if (BigInt(changes) === 0n && this.transactionChanges) return;
2188
+ const tableNames = [tableName, ...this.tablesChangedByForeignKeyActions(tableName)];
2189
+ this.forgetLinesOfGoneRows(tableNames);
2190
+ if (this.transactionChanges) {
2191
+ if (this.transactionChanges !== "all") for (const name of tableNames) this.transactionChanges.add(name);
2192
+ return;
2193
+ }
2194
+ for (const name of tableNames) this.syncTable(name).catch((err) => {
2195
+ console.error(`Failed to sync table ${name}:`, err);
2196
+ });
2197
+ }
2198
+ /**
2199
+ * The tables whose rows an ON DELETE / ON UPDATE action can change when a table's rows change,
2200
+ * following the actions on to the tables they change in turn
2201
+ */
2202
+ tablesChangedByForeignKeyActions(tableName) {
2203
+ const found = /* @__PURE__ */ new Set();
2204
+ const visit = (referenced) => {
2205
+ for (const [name, schema] of this.schemas) {
2206
+ if (found.has(name) || name === tableName) continue;
2207
+ if ((schema.foreignKeys ?? []).some((fk) => fk.references.table === referenced && [fk.onDelete, fk.onUpdate].some((action) => action === "CASCADE" || action === "SET NULL"))) {
2208
+ found.add(name);
2209
+ visit(name);
2210
+ }
2211
+ }
2212
+ };
2213
+ visit(tableName);
2214
+ return Array.from(found);
2215
+ }
2216
+ tablesChangedInTransaction() {
2217
+ const changes = this.transactionChanges;
2218
+ return changes === "all" ? Array.from(this.schemas.keys()) : Array.from(changes ?? []);
2219
+ }
2220
+ /**
2221
+ * Write several tables back, checking every file before writing any, so a file changed on disk
2222
+ * fails the write-back before it has written part of it
2223
+ */
2224
+ async writeBackTogether(tableNames) {
2225
+ await this.waitForPendingSyncs();
2226
+ const prepared = [];
2227
+ for (const tableName of tableNames) prepared.push(...await this.prepareWriteBack(tableName));
2228
+ return this.writeFilesTogether(prepared);
2229
+ }
2230
+ async writeFilesTogether(prepared) {
2231
+ const written = [];
2232
+ try {
2233
+ for (const table of prepared) {
2234
+ written.push(table);
2235
+ await this.writePrepared(table);
2236
+ }
2237
+ } catch (error) {
2238
+ throw await this.restoreAll(written, error);
2239
+ }
2240
+ for (const { tableName, jsonlPath, generation, rowids } of written) {
2241
+ if ((this.changeGenerations.get(tableName) ?? 0) === generation) {
2242
+ this.fieldChanges.delete(tableName);
2243
+ this.rawSqlTables.delete(tableName);
2244
+ }
2245
+ if (rowids) {
2246
+ const origins = this.rowOriginsByRowid.get(tableName);
2247
+ rowids.forEach((rowid, rowIndex) => origins.set(rowid, {
2248
+ file: jsonlPath,
2249
+ rowIndex
2250
+ }));
2251
+ if (!this.scannedJsonlFiles.includes(jsonlPath)) this.scannedJsonlFiles.push(jsonlPath);
2252
+ }
2253
+ }
2254
+ return written;
2255
+ }
2256
+ /**
2257
+ * Put back every written file, going on past one that cannot be put back, and give the error to
2258
+ * throw: the one that made the write-back fail, naming the files left holding what was written
2259
+ */
2260
+ async restoreAll(written, error) {
2261
+ const notRestored = [];
2262
+ for (const table of written) await this.restorePrepared(table).catch(() => notRestored.push(table.jsonlPath));
2263
+ if (notRestored.length === 0) return error;
2264
+ const failure = toError(error);
2265
+ const recoveryError = new Error(`${failure.message}\nThese files could not be put back and hold rows the database does not: ${notRestored.join(", ")}`, { cause: error });
2266
+ if (failure.name === "JsonlConflictError") {
2267
+ recoveryError.name = failure.name;
2268
+ recoveryError.file = failure.file;
2269
+ }
2270
+ return recoveryError;
2271
+ }
2272
+ /**
2273
+ * Put back the content a file held before {@link writePrepared} wrote over it. The file is expected
2274
+ * to hold that content even when putting it back fails, so a file left holding the written rows
2275
+ * counts as changed on disk instead of matching the database
2276
+ */
2277
+ async restorePrepared({ jsonlPath, previousContent, rows, completed }) {
2278
+ if (this.hasSeveralDataDirs() || this.config.writeDataSets) {
2279
+ if (!completed) return;
2280
+ if (await readFile(jsonlPath, "utf8").catch((error) => {
2281
+ if (error.code === "ENOENT") return void 0;
2282
+ throw error;
2283
+ }) !== JsonlWriter.serialize(rows)) throw new Error(`JSONL file '${jsonlPath}' changed during rollback`);
2284
+ }
2285
+ if (previousContent === void 0) {
2286
+ this.fileHashes.delete(jsonlPath);
2287
+ this.observedHashes.delete(jsonlPath);
2288
+ if (this.hasSeveralDataDirs() || this.config.writeDataSets) await replaceFile(jsonlPath, void 0, JsonlWriter.serialize(rows));
2289
+ else await rm(jsonlPath, { force: true });
2290
+ return;
2291
+ }
2292
+ this.fileHashes.set(jsonlPath, hashJsonlContent(previousContent));
2293
+ this.observedHashes.set(jsonlPath, hashJsonlContent(previousContent));
2294
+ if (this.hasSeveralDataDirs() || this.config.writeDataSets) await replaceFile(jsonlPath, (temporary) => writeFile(temporary, previousContent, "utf8"), JsonlWriter.serialize(rows));
2295
+ else await writeFile(jsonlPath, previousContent, "utf-8");
2296
+ }
2297
+ /**
2298
+ * Lay the rows out over the lines the JSONL file already holds.
2299
+ *
2300
+ * Rows keep the order the file lists them in - the database returns rows in its own order, and
2301
+ * an integer primary key is SQLite's rowid, so writing rows back in query order would reshuffle
2302
+ * the file. Rows the file never had follow, in database order.
2303
+ *
2304
+ * With `fields`, only those fields are taken from the row and every other field keeps the value
2305
+ * its line already had, so values a validation hook computed and fields the file omitted are
2306
+ * never materialized. Fields this table does not have are simply not written, so one list can
2307
+ * cover a directory of tables that do not all share it; a sync asked for a single table by name
2308
+ * rejects them instead, since there the caller named both the table and the fields.
2309
+ */
2310
+ mergeWithExistingLines(tableName, existingRows, rows, options) {
2311
+ if (rows.length === 0) return rows;
2312
+ const { fields } = options;
2313
+ const tableFields = fields?.filter((field) => rows.some((row) => field in row));
2314
+ if (fields && tableFields && options.strictFields && tableFields.length < fields.length) {
2315
+ const unknownFields = fields.filter((field) => !tableFields.includes(field));
2316
+ throw new Error(`Cannot write back field(s) [${unknownFields.join(", ")}] for table '${tableName}': no such field in the rows written back to the file.`);
2317
+ }
2318
+ const existing = options.matches ?? this.matchExistingRows(tableName, rows, existingRows, { required: fields !== void 0 });
2319
+ if (!existing) return rows;
2320
+ const rowByLine = /* @__PURE__ */ new Map();
2321
+ const newRows = [];
2322
+ rows.forEach((row, index) => {
2323
+ const base = existing[index];
2324
+ if (base) rowByLine.set(base, row);
2325
+ else newRows.push(row);
2326
+ });
2327
+ return [...existingRows.filter((base) => rowByLine.has(base)).map((base) => {
2328
+ const row = rowByLine.get(base);
2329
+ return tableFields ? mergeFields(base, row, {
2330
+ fields: tableFields,
2331
+ keyOrder: this.keyOrders.get(tableName)
2332
+ }) : row;
2333
+ }), ...newRows];
2334
+ }
2335
+ /**
2336
+ * Pair each row with the JSONL line it came from, indexed the same way as `rows`.
2337
+ * Returns undefined when the rows cannot be matched and the caller can do without it.
2338
+ */
2339
+ matchExistingRows(tableName, rows, existingRows, options) {
2340
+ if (existingRows.length === 0) return rows.map(() => void 0);
2341
+ const pkName = this.schemas.get(tableName)?.columns.find((col) => col.primaryKey)?.name;
2342
+ const pkValues = pkName ? existingRows.map((row) => row[pkName]) : [];
2343
+ if (pkName !== void 0 && pkValues.every((value) => value !== void 0 && value !== null) && new Set(pkValues.map((value) => String(value))).size === pkValues.length) {
2344
+ const byPk = new Map(existingRows.map((row, index) => [String(pkValues[index]), row]));
2345
+ return rows.map((row) => {
2346
+ const pkValue = row[pkName];
2347
+ return pkValue === void 0 || pkValue === null ? void 0 : byPk.get(String(pkValue));
2348
+ });
2349
+ }
2350
+ if (rows.length !== existingRows.length) {
2351
+ if (!options.required) return;
2352
+ throw new Error(`Cannot write back selected fields for table '${tableName}': the file has ${existingRows.length} row(s) but the table has ${rows.length}, and ${pkName ? `column '${pkName}' is not usable as a primary key in the file` : "the table has no primary key"}, so rows cannot be matched to their existing lines.`);
2353
+ }
2354
+ return existingRows;
2355
+ }
2356
+ /**
2357
+ * Read the rows a JSONL file currently holds, treating a missing file as empty, and refuse to go on
2358
+ * when the file is not the one this database last read or wrote: writing over it would drop the
2359
+ * changes made to it since
2360
+ */
2361
+ async readUnchangedRows(jsonlPath) {
2362
+ const result = await JsonlReader.readSnapshot(jsonlPath);
2363
+ if (!result.ok && result.error.code !== "ENOENT") throw result.error;
2364
+ const snapshot = result.ok ? result.value : {
2365
+ rows: ok([]),
2366
+ contentHash: void 0
2367
+ };
2368
+ const knownHash = this.fileHashes.get(jsonlPath);
2369
+ if (knownHash !== void 0 && snapshot.contentHash !== knownHash || this.config.writeDataSets && !this.scannedJsonlFiles.includes(jsonlPath) && snapshot.contentHash !== void 0) {
2370
+ const conflictError = /* @__PURE__ */ new Error(`JSONL file '${jsonlPath}' was changed after the database read it, so it was not overwritten. Create the database again and call initialize() to load the current file, then retry the write.`);
2371
+ conflictError.name = "JsonlConflictError";
2372
+ conflictError.file = jsonlPath;
2373
+ throw conflictError;
2374
+ }
2375
+ return unwrap(snapshot.rows);
2376
+ }
2377
+ /**
2378
+ * Tell whether the files the tables were loaded from changed since this database last read or
2379
+ * wrote them: a JSONL file was edited, added or removed, or a table's schema file was edited, added
2380
+ * or removed. When they did, the database holds rows or a schema the files no longer have; create it
2381
+ * again and call initialize() to load the current files.
2382
+ */
2383
+ async hasExternalChanges() {
2384
+ try {
2385
+ return ok((await this.findExternalChangesInternal()).length > 0);
2386
+ } catch (error) {
2387
+ return err(toError(error));
2388
+ }
2389
+ }
2390
+ /**
2391
+ * The files that changed since this database last read or wrote them, as {@link hasExternalChanges}
2392
+ * tells: each JSONL file edited, added or removed, and each schema file edited, added or removed
2393
+ */
2394
+ async findExternalChanges() {
2395
+ try {
2396
+ return ok(await this.findExternalChangesInternal());
2397
+ } catch (error) {
2398
+ return err(toError(error));
2399
+ }
2400
+ }
2401
+ async findExternalChangesInternal() {
2402
+ await this.waitForPendingSyncs();
2403
+ const changed = /* @__PURE__ */ new Set();
2404
+ for (const [file, knownHash] of this.observedHashes) {
2405
+ const content = await readFile(file, "utf-8").catch((error) => {
2406
+ if (error.code === "ENOENT") return void 0;
2407
+ throw error;
2408
+ });
2409
+ if (content === void 0 || hashJsonlContent(content) !== knownHash) changed.add(file);
2410
+ }
2411
+ const tables = await DirectoryScanner.scanDirectory(this.config.dataDir);
2412
+ const scanned = new Set(listJsonlFiles(tables));
2413
+ for (const file of this.scannedJsonlFiles) if (!scanned.has(file)) changed.add(file);
2414
+ for (const file of scanned) if (!this.scannedJsonlFiles.includes(file)) changed.add(file);
2415
+ for (const name of /* @__PURE__ */ new Set([...this.schemaFileStates.keys(), ...tables.keys()])) {
2416
+ const knownState = this.schemaFileStates.get(name) ?? "";
2417
+ const config = tables.get(name);
2418
+ const state = config ? await this.schemaFileState(name, config) : await this.stateOfKnownSchemaFile(knownState);
2419
+ if (state !== knownState) changed.add((state || knownState).split("\0")[0]);
2420
+ }
2421
+ return [...changed];
2422
+ }
2423
+ /** The state of the schema file a state names, for a table whose JSONL file is gone */
2424
+ async stateOfKnownSchemaFile(knownState) {
2425
+ if (!knownState) return "";
2426
+ const schemaPath = knownState.split("\0")[0];
2427
+ const content = await readFile(schemaPath, "utf-8").catch((error) => {
2428
+ if (error.code === "ENOENT") return void 0;
2429
+ throw error;
2430
+ });
2431
+ return content === void 0 ? "" : `${schemaPath}\0${hashJsonlContent(content)}`;
2432
+ }
2433
+ async schemaFileState(tableName, config) {
2434
+ if (config.validationSchema) return "";
2435
+ const schemaPath = await this.findTableSchemaFile(tableName, config);
2436
+ if (!schemaPath) return "";
2437
+ return `${schemaPath}\0${hashJsonlContent(await readFile(schemaPath, "utf-8"))}`;
2438
+ }
2439
+ /**
2440
+ * Sync database changes back to JSONL files
2441
+ * Uses backward transformation when available
2442
+ * @param tableName Optional table name to sync. If not provided, syncs all loaded tables
2443
+ * @param options Optional sync options, e.g. the fields to write back
2444
+ */
2445
+ async sync(tableName, options) {
2446
+ try {
2447
+ await this.syncInternal(tableName, options);
2448
+ return ok(void 0);
2449
+ } catch (error) {
2450
+ return err(toError(error));
2451
+ }
2452
+ }
2453
+ async syncInternal(tableName, options) {
2454
+ this.refuseWhileTransactionSettles("sync");
2455
+ this.assertWritable(tableName);
2456
+ if (this.inTransaction) throw new Error("sync() is not supported inside a transaction: the transaction writes back the tables it changed once it commits, and a file written earlier would keep rows it rolls back");
2457
+ if (tableName) {
2458
+ if (!this.schemas.has(tableName)) throw new Error(`Table '${tableName}' is not loaded`);
2459
+ await this.syncTable(tableName, {
2460
+ ...options,
2461
+ strictFields: options?.fields !== void 0
2462
+ });
2463
+ } else for (const [name] of this.schemas) await this.syncTable(name, options);
2464
+ }
2465
+ /**
2466
+ * Execute a function within a transaction
2467
+ * Automatically commits on success or rolls back on error.
2468
+ *
2469
+ * Note: `tx` (the argument `fn` receives) is the same Result-returning API as `this` - a failed
2470
+ * `tx.insert()`/`tx.update()`/etc. inside `fn` does not throw and therefore does not roll back the
2471
+ * transaction on its own. To abort on such a failure, check the Result and `throw result.error`
2472
+ * (or any error) from `fn`; only a thrown error rolls the transaction back.
2473
+ */
2474
+ async transaction(fn) {
2475
+ if (this.inTransaction || this.transactionStarting) return err(/* @__PURE__ */ new Error("Nested transactions are not supported"));
2476
+ this.transactionStarting = true;
2477
+ const token = {};
2478
+ let fieldChangesBefore;
2479
+ let rawSqlTablesBefore;
2480
+ let linesWithUnknownFieldsBefore;
2481
+ let originsBefore;
2482
+ const scannedBefore = [...this.scannedJsonlFiles];
2483
+ let written = [];
2484
+ try {
2485
+ await this.waitForPendingSyncs();
2486
+ originsBefore = new Map([...this.rowOriginsByRowid].map(([name, origins]) => [name, new Map(origins)]));
2487
+ fieldChangesBefore = cloneFieldChanges(this.fieldChanges);
2488
+ rawSqlTablesBefore = new Set(this.rawSqlTables);
2489
+ linesWithUnknownFieldsBefore = new Map(Array.from(this.linesWithUnknownFields, ([tableName, lines]) => [tableName, new Map(lines)]));
2490
+ this.db.exec("BEGIN TRANSACTION");
2491
+ this.inTransaction = true;
2492
+ this.transactionToken = token;
2493
+ this.transactionStarting = false;
2494
+ this.transactionChanges = /* @__PURE__ */ new Set();
2495
+ let result;
2496
+ try {
2497
+ result = await fn(this.scopedToTransaction(token));
2498
+ } finally {
2499
+ this.transactionClosing = true;
2500
+ }
2501
+ if (!this.isReadOnlyDataSet()) written = await this.writeBackTogether(this.tablesChangedInTransaction());
2502
+ this.db.exec("COMMIT");
2503
+ this.inTransaction = false;
2504
+ this.transactionChanges = void 0;
2505
+ return ok(result);
2506
+ } catch (error) {
2507
+ this.transactionStarting = false;
2508
+ this.transactionChanges = void 0;
2509
+ if (originsBefore) this.rowOriginsByRowid = originsBefore;
2510
+ this.scannedJsonlFiles = scannedBefore;
2511
+ if (fieldChangesBefore) this.fieldChanges = fieldChangesBefore;
2512
+ if (rawSqlTablesBefore) this.rawSqlTables = rawSqlTablesBefore;
2513
+ if (linesWithUnknownFieldsBefore) this.linesWithUnknownFields = linesWithUnknownFieldsBefore;
2514
+ const failure = await this.restoreAll(written, error);
2515
+ if (this.inTransaction) try {
2516
+ this.db.exec("ROLLBACK");
2517
+ } catch (_rollbackError) {}
2518
+ this.inTransaction = false;
2519
+ return err(toError(failure));
2520
+ } finally {
2521
+ this.transactionClosing = false;
2522
+ this.transactionToken = void 0;
2523
+ }
2524
+ }
2525
+ /**
2526
+ * The object a transaction() callback receives. Calls on it are marked as the transaction's own for as
2527
+ * long as they run; a write made through the database itself in the meantime is refused, since writes are
2528
+ * synchronous and cannot be queued until the transaction ends
2529
+ */
2530
+ scopedToTransaction(token) {
2531
+ return new Proxy(this, { get: (target, property) => {
2532
+ const value = Reflect.get(target, property, target);
2533
+ if (typeof value !== "function") return value;
2534
+ return (...args) => {
2535
+ const before = target.viaTransactionObject;
2536
+ target.viaTransactionObject = before || target.transactionToken === token;
2537
+ try {
2538
+ return value.apply(target, args);
2539
+ } finally {
2540
+ target.viaTransactionObject = before;
2541
+ }
2542
+ };
2543
+ } });
2544
+ }
2545
+ /**
2546
+ * Wait for every queued sync to finish, so a fire-and-forget auto-sync is not dropped
2547
+ */
2548
+ async waitForPendingSyncs() {
2549
+ const awaited = /* @__PURE__ */ new Set();
2550
+ let pending = Array.from(this.syncQueue.values());
2551
+ while (pending.length > 0) {
2552
+ for (const promise of pending) awaited.add(promise);
2553
+ await Promise.all(pending);
2554
+ pending = Array.from(this.syncQueue.values()).filter((promise) => !awaited.has(promise));
2555
+ }
2556
+ }
2557
+ /**
2558
+ * Close the database connection
2559
+ */
2560
+ async close() {
2561
+ try {
2562
+ await this.waitForPendingSyncs();
2563
+ try {
2564
+ this.db.close();
2565
+ } catch (_error) {}
2566
+ return ok(void 0);
2567
+ } catch (error) {
2568
+ return err(toError(error));
2569
+ }
2570
+ }
2571
+ /**
2572
+ * Get a handle for running SQL on the underlying SQLite database. It wraps the connection rather than
2573
+ * being it, also outside a transaction: while a transaction() callback runs, SQL that changes rows is
2574
+ * refused unless the handle came from the callback's `tx`, and SQL that would end the transaction is
2575
+ * refused for every handle. Outside a transaction it runs SQL unchanged.
2576
+ */
2577
+ getDb() {
2578
+ const token = this.viaTransactionObject ? this.transactionToken : void 0;
2579
+ const viaTransaction = () => token !== void 0 && token === this.transactionToken;
2580
+ const idle = () => !this.inTransaction && !this.transactionStarting && !this.transactionClosing;
2581
+ const guarded = (sql, run) => {
2582
+ if (idle() && !this.hasSeveralDataDirs()) return run();
2583
+ this.refuseUnsafeSql(sql, viaTransaction());
2584
+ return this.readOnlyWhileTransactionSettles(() => this.trackRawSql(run), viaTransaction());
2585
+ };
2586
+ return {
2587
+ prepare: (sql) => {
2588
+ if (!idle() || this.hasSeveralDataDirs()) this.refuseUnsafeSql(sql, viaTransaction());
2589
+ const statement = this.readOnlyWhileTransactionSettles(() => this.db.prepare(sql), viaTransaction());
2590
+ return {
2591
+ run: (...params) => guarded(sql, () => statement.run(...params)),
2592
+ get: (...params) => guarded(sql, () => statement.get(...params)),
2593
+ all: (...params) => guarded(sql, () => statement.all(...params))
2594
+ };
2595
+ },
2596
+ exec: (sql) => guarded(sql, () => this.db.exec(sql)),
2597
+ close: () => this.db.close()
2598
+ };
2599
+ }
2600
+ };
2601
+ function listJsonlFiles(tables) {
2602
+ return Array.from(tables.values()).flatMap((config) => config.jsonlPaths ?? [config.jsonlPath]).sort();
2603
+ }
2604
+ //#endregion
2605
+ //#region src/error-formatter.ts
2606
+ var ErrorFormatter = class {
2607
+ verbose;
2608
+ constructor(options = {}) {
2609
+ this.verbose = options.verbose ?? false;
2610
+ }
2611
+ /**
2612
+ * Format validation errors
2613
+ */
2614
+ formatValidationErrors(errors) {
2615
+ if (this.verbose) return this.formatValidationErrorsVerbose(errors);
2616
+ return this.formatValidationErrorsCompact(errors);
2617
+ }
2618
+ /**
2619
+ * Format foreign key error
2620
+ */
2621
+ formatForeignKeyError(error) {
2622
+ if (this.verbose) return this.formatForeignKeyErrorVerbose(error);
2623
+ return this.formatForeignKeyErrorCompact(error);
2624
+ }
2625
+ /**
2626
+ * Format compact (default) validation errors
2627
+ */
2628
+ formatValidationErrorsCompact(errors) {
2629
+ const lines = [];
2630
+ for (const error of errors) for (const issue of error.issues) {
2631
+ const fieldPath = this.getFieldPath(issue);
2632
+ const line = `${error.file}:${error.rowIndex + 1} • ${fieldPath}: ${issue.message}`;
2633
+ lines.push(line);
2634
+ }
2635
+ return lines.join("\n");
2636
+ }
2637
+ /**
2638
+ * Format verbose validation errors
2639
+ */
2640
+ formatValidationErrorsVerbose(errors) {
2641
+ const blocks = [];
2642
+ for (let i = 0; i < errors.length; i++) {
2643
+ const error = errors[i];
2644
+ const isLast = i === errors.length - 1;
2645
+ const prefix = isLast ? "└─" : "├─";
2646
+ const linePrefix = isLast ? " " : "│ ";
2647
+ const lines = [`${prefix} ${error.file}:${error.rowIndex + 1}`];
2648
+ for (const issue of error.issues) {
2649
+ const fieldPath = this.getFieldPath(issue);
2650
+ lines.push(`${linePrefix}Field: ${fieldPath}`);
2651
+ lines.push(`${linePrefix}Error: ${issue.message}`);
2652
+ }
2653
+ if (error.originalData !== void 0) lines.push(`${linePrefix}Original data: ${JSON.stringify(error.originalData)}`);
2654
+ if (error.data !== void 0) {
2655
+ const label = error.originalData !== void 0 ? "Transformed data" : "Data";
2656
+ lines.push(`${linePrefix}${label}: ${JSON.stringify(error.data)}`);
2657
+ }
2658
+ blocks.push(lines.join("\n"));
2659
+ }
2660
+ return blocks.join("\n│\n");
2661
+ }
2662
+ /**
2663
+ * Format compact foreign key error
2664
+ */
2665
+ formatForeignKeyErrorCompact(error) {
2666
+ return `${error.file}:${error.rowIndex + 1} • ${error.column}: Foreign key constraint failed - Referenced value ${JSON.stringify(error.value)} does not exist in ${error.referencedTable}(${error.referencedColumn})`;
2667
+ }
2668
+ /**
2669
+ * Format verbose foreign key error
2670
+ */
2671
+ formatForeignKeyErrorVerbose(error) {
2672
+ const lines = [
2673
+ `└─ ${error.file}:${error.rowIndex + 1}`,
2674
+ ` Type: Foreign Key Violation`,
2675
+ ` Field: ${error.column}`,
2676
+ ` Value: ${JSON.stringify(error.value)}`,
2677
+ ` References: ${error.referencedTable}(${error.referencedColumn})`,
2678
+ ` Error: Referenced value does not exist in target table`
2679
+ ];
2680
+ if (error.data !== void 0) lines.push(` Data: ${JSON.stringify(error.data)}`);
2681
+ return lines.join("\n");
2682
+ }
2683
+ /**
2684
+ * Get field path from issue
2685
+ */
2686
+ getFieldPath(issue) {
2687
+ if (!issue.path || issue.path.length === 0) return "root";
2688
+ return issue.path.map((segment) => {
2689
+ if (typeof segment === "object" && segment !== null && "key" in segment) return String(segment.key);
2690
+ return String(segment);
2691
+ }).join(".");
2692
+ }
2693
+ /**
2694
+ * Format error header with count
2695
+ */
2696
+ formatErrorHeader(count, file) {
2697
+ const fileInfo = file ? ` in ${file}` : "";
2698
+ return styleText("red", `✗ Found ${count} error(s)${fileInfo}`);
2699
+ }
2700
+ /**
2701
+ * Format migration failure header
2702
+ */
2703
+ formatMigrationFailureHeader() {
2704
+ return styleText("red", "\n✗ Migration failed and was rolled back");
2705
+ }
2706
+ };
2707
+ //#endregion
2708
+ //#region src/fill.ts
2709
+ /**
2710
+ * Fill the named fields into the rows of the JSONL files that have no value for them, with the values
2711
+ * each table computes for a row. A value already in the file is never replaced, and a line that gains
2712
+ * nothing is left byte for byte; a line that does gain a value is written with its keys in the order
2713
+ * the computed row lists them. Every value is computed before any file is written.
2714
+ */
2715
+ async function fillFields(options) {
2716
+ try {
2717
+ return ok(await fillFieldsInternal(options));
2718
+ } catch (error) {
2719
+ return err(toError(error));
2720
+ }
2721
+ }
2722
+ async function fillFieldsInternal(options) {
2723
+ if (options.fields && options.fields.length === 0) throw new Error("No fields to fill. Name at least one field.");
2724
+ const { dataDir, tableNames } = await resolveTables(options.path);
2725
+ const schemaDir = options.schemaDir ?? dataDir;
2726
+ const loadFiller = options.loadFiller ?? fillerFromValidationSchema;
2727
+ const tablesWithoutSchema = [];
2728
+ const tables = [];
2729
+ for (const table of tableNames) {
2730
+ const schemaPath = await findSchemaFile(schemaDir, table);
2731
+ if (!schemaPath) {
2732
+ tablesWithoutSchema.push(table);
2733
+ continue;
2734
+ }
2735
+ const schemaModule = await import(`${pathToFileURL(schemaPath).href}?t=${Date.now()}`);
2736
+ tables.push({
2737
+ table,
2738
+ fields: options.fields ?? [primaryKeyOf(schemaModule)],
2739
+ fill: loadFiller(schemaModule, {
2740
+ tableName: table,
2741
+ schemaPath
2742
+ })
2743
+ });
2744
+ }
2745
+ const produced = /* @__PURE__ */ new Set();
2746
+ const unreadableLines = [];
2747
+ const filled = [];
2748
+ const writes = [];
2749
+ for (const { table, fields, fill } of tables) {
2750
+ const file = join(dataDir, `${table}.jsonl`);
2751
+ const read = await readFile(file, "utf-8");
2752
+ const bom = read.startsWith("") ? "" : "";
2753
+ const lines = splitLines(read.slice(bom.length));
2754
+ const written = /* @__PURE__ */ new Set();
2755
+ const unreadable = [];
2756
+ let count = 0;
2757
+ lines.forEach((line, index) => {
2758
+ if (!line.row) {
2759
+ if (line.text.trim() !== "") unreadable.push(index + 1);
2760
+ return;
2761
+ }
2762
+ const computed = fill(structuredClone(line.row));
2763
+ const gained = fields.filter((field) => {
2764
+ if (isBlank(ownValue(computed, field))) return false;
2765
+ produced.add(field);
2766
+ return ownValue(line.row, field) === void 0 || ownValue(line.row, field) === null;
2767
+ });
2768
+ if (gained.length === 0) return;
2769
+ for (const field of gained) {
2770
+ setField(line.row, field, computed[field]);
2771
+ written.add(field);
2772
+ }
2773
+ line.text = serializeRow(line.row, Object.keys(computed));
2774
+ count += 1;
2775
+ });
2776
+ if (unreadable.length > 0) unreadableLines.push({
2777
+ file,
2778
+ lines: unreadable
2779
+ });
2780
+ if (count === 0) continue;
2781
+ writes.push({
2782
+ file,
2783
+ read,
2784
+ content: bom + lines.map((line) => `${line.text}${line.eol}`).join("")
2785
+ });
2786
+ filled.push({
2787
+ table,
2788
+ file,
2789
+ fields: [...written],
2790
+ count
2791
+ });
2792
+ }
2793
+ for (const { file, read } of writes) if (await readFile(file, "utf-8") !== read) {
2794
+ const error = /* @__PURE__ */ new Error(`JSONL file '${file}' was changed after it was read, so no file was filled. Run the fill again.`);
2795
+ error.name = "JsonlConflictError";
2796
+ error.file = file;
2797
+ throw error;
2798
+ }
2799
+ await replaceAll(writes);
2800
+ const named = options.fields ?? [...new Set(tables.flatMap(({ fields }) => fields))];
2801
+ return {
2802
+ filled,
2803
+ tablesWithoutSchema,
2804
+ unreadableLines,
2805
+ unproducedFields: tableNames.length > 0 ? named.filter((field) => !produced.has(field)) : []
2806
+ };
2807
+ }
2808
+ /**
2809
+ * Write every file or none: each content goes to a temporary file first, the temporaries replace the
2810
+ * files once all are written, and the files already replaced are put back when a later one fails
2811
+ */
2812
+ async function replaceAll(writes) {
2813
+ const staged = writes.map((write) => ({
2814
+ ...write,
2815
+ temporary: `${write.file}.${randomBytes(6).toString("hex")}.tmp`
2816
+ }));
2817
+ const replaced = [];
2818
+ try {
2819
+ for (const { file, temporary, content } of staged) {
2820
+ await writeFile(temporary, content, "utf-8");
2821
+ await chmod(temporary, (await stat(file)).mode & 4095);
2822
+ }
2823
+ for (const write of staged) {
2824
+ await rename(write.temporary, write.file);
2825
+ replaced.push(write);
2826
+ }
2827
+ } catch (error) {
2828
+ const notRestored = [];
2829
+ for (const { file, read } of replaced) await writeFile(file, read, "utf-8").catch(() => notRestored.push(file));
2830
+ await Promise.all(staged.map(({ temporary }) => rm(temporary, { force: true })));
2831
+ if (notRestored.length === 0) throw error;
2832
+ throw new Error(`${toError(error).message}\nThese files could not be put back and stay filled: ${notRestored.join(", ")}`, { cause: error });
2833
+ }
2834
+ }
2835
+ async function resolveTables(path) {
2836
+ const stats = await stat(path);
2837
+ if (stats.isDirectory()) return {
2838
+ dataDir: path,
2839
+ tableNames: (await readdir(path)).filter((entry) => entry.endsWith(".jsonl")).map((entry) => basename(entry, ".jsonl")).sort()
2840
+ };
2841
+ if (stats.isFile() && path.endsWith(".jsonl")) return {
2842
+ dataDir: dirname(path),
2843
+ tableNames: [basename(path, ".jsonl")]
2844
+ };
2845
+ throw new Error(`Invalid path: ${path}. Must be a directory or .jsonl file.`);
2846
+ }
2847
+ function primaryKeyOf(schemaModule) {
2848
+ const primaryKey = (schemaModule.schema ?? schemaModule.default)?.primaryKey ?? schemaModule.primaryKey;
2849
+ return typeof primaryKey === "string" ? primaryKey : "id";
2850
+ }
2851
+ function fillerFromValidationSchema(schemaModule, { schemaPath }) {
2852
+ const schema = schemaModule.schema ?? schemaModule.default;
2853
+ if (!schema || typeof schema !== "object" || !("~standard" in schema)) throw new Error(`${schemaPath} does not export a StandardSchema as \`schema\` or as its default export`);
2854
+ return (row) => {
2855
+ const result = schema["~standard"].validate(row);
2856
+ if (result instanceof Promise) throw new Error(`${schemaPath}: asynchronous validation is not supported`);
2857
+ if (result.issues) return {};
2858
+ return hasBackward(schema) ? schema.backward(result.value) : result.value;
2859
+ };
2860
+ }
2861
+ function ownValue(row, field) {
2862
+ return Object.hasOwn(row, field) ? row[field] : void 0;
2863
+ }
2864
+ function setField(row, field, value) {
2865
+ Object.defineProperty(row, field, {
2866
+ value,
2867
+ enumerable: true,
2868
+ writable: true,
2869
+ configurable: true
2870
+ });
2871
+ }
2872
+ function isBlank(value) {
2873
+ if (value === void 0 || value === null) return true;
2874
+ if (typeof value !== "object" || Array.isArray(value)) return false;
2875
+ return Object.values(value).every(isBlank);
2876
+ }
2877
+ function splitLines(content) {
2878
+ if (content === "") return [];
2879
+ return content.split("\n").map((raw, index, all) => {
2880
+ const carriage = raw.endsWith("\r") ? "\r" : "";
2881
+ const text = carriage ? raw.slice(0, -1) : raw;
2882
+ let row;
2883
+ if (text.trim() !== "") try {
2884
+ const parsed = JSON.parse(text);
2885
+ row = parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
2886
+ } catch {
2887
+ row = void 0;
2888
+ }
2889
+ return {
2890
+ text,
2891
+ eol: index === all.length - 1 ? carriage : `${carriage}\n`,
2892
+ row
2893
+ };
2894
+ });
2895
+ }
2896
+ /** The row with its keys in the order the computed row lists them, and keys it does not list after those */
2897
+ function serializeRow(row, fieldOrder) {
2898
+ const rank = new Map(fieldOrder.map((field, index) => [field, index]));
2899
+ const rankOf = (key) => rank.get(key) ?? fieldOrder.length;
2900
+ const ordered = Object.entries(row).sort(([a], [b]) => rankOf(a) - rankOf(b));
2901
+ const out = {};
2902
+ for (const [key, value] of ordered) setField(out, key, value);
2903
+ return JSON.stringify(out);
2904
+ }
2905
+ //#endregion
2906
+ //#region src/cli.ts
2907
+ register("amaro/transform", import.meta.url);
2908
+ const originalEmitWarning = process.emitWarning;
2909
+ process.emitWarning = (warning, ...args) => {
2910
+ if (typeof warning === "string" && warning.startsWith("SQLite") && args[0] === "ExperimentalWarning") return;
2911
+ originalEmitWarning(warning, ...args);
2912
+ };
2913
+ const SANDBOX_GLOBALS = Object.freeze({
2914
+ console: Object.freeze({
2915
+ log: console.log.bind(console),
2916
+ warn: console.warn.bind(console),
2917
+ error: console.error.bind(console),
2918
+ info: console.info.bind(console)
2919
+ }),
2920
+ Math,
2921
+ Number,
2922
+ String,
2923
+ Boolean,
2924
+ Date,
2925
+ JSON,
2926
+ RegExp,
2927
+ Array,
2928
+ Object
2929
+ });
2930
+ function runInSandbox(expression, context = {}) {
2931
+ const sandbox = Object.create(null);
2932
+ Object.assign(sandbox, SANDBOX_GLOBALS, context);
2933
+ sandbox.globalThis = sandbox;
2934
+ return runInNewContext(expression, sandbox, { timeout: 1e3 });
2935
+ }
2936
+ const generateCommand = defineCommand({
2937
+ name: "generate",
2938
+ description: "Generate TypeScript type definitions from schema files",
2939
+ args: z.object({
2940
+ dataDir: arg(z.string(), {
2941
+ positional: true,
2942
+ description: "Directory containing JSONL and schema files"
2943
+ }),
2944
+ output: arg(z.string().optional(), {
2945
+ alias: "o",
2946
+ description: "Output file path (default: db.ts in dataDir)"
2947
+ })
2948
+ }),
2949
+ run: async (args) => {
2950
+ try {
2951
+ await new TypeGenerator({
2952
+ dataDir: args.dataDir,
2953
+ output: args.output
2954
+ }).generate();
2955
+ console.log("Type generation completed successfully!");
2956
+ } catch (error) {
2957
+ console.error("Error:", error instanceof Error ? error.message : String(error));
2958
+ process.exit(1);
2959
+ }
2960
+ }
2961
+ });
2962
+ const validateCommand = defineCommand({
2963
+ name: "validate",
2964
+ description: "Validate JSONL file(s) against schema",
2965
+ args: z.object({
2966
+ path: arg(z.string(), {
2967
+ positional: true,
2968
+ description: "File or directory path to validate"
2969
+ }),
2970
+ verbose: arg(z.boolean().default(false), {
2971
+ alias: "v",
2972
+ description: "Show verbose error output"
2973
+ })
2974
+ }),
2975
+ run: async (args) => {
2976
+ try {
2977
+ const stats = await stat(args.path);
2978
+ let dataDir;
2979
+ let tableName;
2980
+ if (stats.isDirectory()) dataDir = args.path;
2981
+ else if (stats.isFile() && args.path.endsWith(".jsonl")) {
2982
+ dataDir = dirname(args.path);
2983
+ tableName = basename(args.path, ".jsonl");
2984
+ } else throw new Error(`Invalid path: ${args.path}. Must be a directory or .jsonl file.`);
2985
+ const db = LinesDB.create({ dataDir });
2986
+ let result;
2987
+ try {
2988
+ result = unwrap(await db.initialize({
2989
+ tableName,
2990
+ detailedValidate: true
2991
+ }));
2992
+ } finally {
2993
+ await db.close();
2994
+ }
2995
+ if (!tableName) {
2996
+ const formatter = new ErrorFormatter({ verbose: args.verbose });
2997
+ for (const tableResult of result.tableResults) if (tableResult.valid && tableResult.warnings.length === 0) console.log(styleText("green", `✓ ${tableResult.tableName} (${tableResult.rowCount} records)`));
2998
+ else if (tableResult.valid && tableResult.warnings.length > 0) for (const warning of tableResult.warnings) console.warn(styleText("yellow", `⚠ ${warning}`));
2999
+ else {
3000
+ const fileErrors = tableResult.errors;
3001
+ console.error(formatter.formatErrorHeader(fileErrors.length, fileErrors[0]?.file));
3002
+ console.error("");
3003
+ const validationErrors = fileErrors.filter((e) => e.type !== "foreignKey" || !e.foreignKeyError);
3004
+ const foreignKeyErrors = fileErrors.filter((e) => e.type === "foreignKey" && e.foreignKeyError);
3005
+ if (validationErrors.length > 0) console.error(formatter.formatValidationErrors(validationErrors.map((e) => ({
3006
+ file: e.file,
3007
+ rowIndex: e.rowIndex,
3008
+ issues: e.issues
3009
+ }))));
3010
+ for (const error of foreignKeyErrors) if (error.foreignKeyError) console.error(formatter.formatForeignKeyError({
3011
+ file: error.file,
3012
+ rowIndex: error.rowIndex,
3013
+ column: error.foreignKeyError.column,
3014
+ value: error.foreignKeyError.value,
3015
+ referencedTable: error.foreignKeyError.referencedTable,
3016
+ referencedColumn: error.foreignKeyError.referencedColumn
3017
+ }));
3018
+ console.error("");
3019
+ }
3020
+ if (result.valid) {
3021
+ console.log("");
3022
+ console.log(styleText("green", "✓ All records are valid"));
3023
+ process.exit(0);
3024
+ } else process.exit(1);
3025
+ } else {
3026
+ if (result.warnings.length > 0) {
3027
+ for (const warning of result.warnings) console.warn(styleText("yellow", `⚠ ${warning}`));
3028
+ console.log("");
3029
+ }
3030
+ if (result.valid) {
3031
+ console.log(styleText("green", "✓ All records are valid"));
3032
+ process.exit(0);
3033
+ } else {
3034
+ const formatter = new ErrorFormatter({ verbose: args.verbose });
3035
+ for (const [, fileErrors] of result.errors.reduce((map, error) => {
3036
+ const errors = map.get(error.file) || [];
3037
+ errors.push(error);
3038
+ map.set(error.file, errors);
3039
+ return map;
3040
+ }, /* @__PURE__ */ new Map())) {
3041
+ console.error(formatter.formatErrorHeader(fileErrors.length, fileErrors[0]?.file));
3042
+ console.error("");
3043
+ const validationErrors = fileErrors.filter((e) => e.type !== "foreignKey" || !e.foreignKeyError);
3044
+ const foreignKeyErrors = fileErrors.filter((e) => e.type === "foreignKey" && e.foreignKeyError);
3045
+ if (validationErrors.length > 0) console.error(formatter.formatValidationErrors(validationErrors.map((e) => ({
3046
+ file: e.file,
3047
+ rowIndex: e.rowIndex,
3048
+ issues: e.issues
3049
+ }))));
3050
+ for (const error of foreignKeyErrors) if (error.foreignKeyError) console.error(formatter.formatForeignKeyError({
3051
+ file: error.file,
3052
+ rowIndex: error.rowIndex,
3053
+ column: error.foreignKeyError.column,
3054
+ value: error.foreignKeyError.value,
3055
+ referencedTable: error.foreignKeyError.referencedTable,
3056
+ referencedColumn: error.foreignKeyError.referencedColumn
3057
+ }));
3058
+ console.error("");
3059
+ }
3060
+ process.exit(1);
3061
+ }
3062
+ }
3063
+ } catch (error) {
3064
+ console.error("Error:", error instanceof Error ? error.message : String(error));
3065
+ process.exit(1);
3066
+ }
3067
+ }
3068
+ });
3069
+ const migrateCommand = defineCommand({
3070
+ name: "migrate",
3071
+ description: "Migrate data with transformation function",
3072
+ args: z.object({
3073
+ path: arg(z.string(), {
3074
+ positional: true,
3075
+ description: "File or directory path to migrate"
3076
+ }),
3077
+ transform: arg(z.string(), {
3078
+ positional: true,
3079
+ description: "Transform function (e.g., \"(row) => ({ ...row, age: row.age + 1 })\")"
3080
+ }),
3081
+ filter: arg(z.string().optional(), {
3082
+ alias: "f",
3083
+ description: "Filter expression"
3084
+ }),
3085
+ fields: arg(z.string().optional(), { description: "Comma-separated fields to write back (e.g. \"id\"). Every other field keeps the value the JSONL file already had. Default: write every field" }),
3086
+ errorOutput: arg(z.string().optional(), {
3087
+ alias: "e",
3088
+ description: "Output file path for transformed data when migration fails"
3089
+ }),
3090
+ verbose: arg(z.boolean().default(false), {
3091
+ alias: "v",
3092
+ description: "Show verbose error output"
3093
+ })
3094
+ }),
3095
+ run: async (args) => {
3096
+ try {
3097
+ const writeBackFields = parseWriteBackFields(args.fields);
3098
+ const stats = await stat(args.path);
3099
+ if (stats.isDirectory()) await migrateDirectory(args.path, args.transform, {
3100
+ filter: args.filter,
3101
+ writeBackFields,
3102
+ errorOutput: args.errorOutput,
3103
+ verbose: args.verbose
3104
+ });
3105
+ else if (stats.isFile() && args.path.endsWith(".jsonl")) await migrateFile(args.path, args.transform, {
3106
+ filter: args.filter,
3107
+ writeBackFields,
3108
+ errorOutput: args.errorOutput,
3109
+ verbose: args.verbose
3110
+ });
3111
+ else {
3112
+ console.error(`Error: Invalid path: ${args.path}. Must be a directory or .jsonl file.`);
3113
+ process.exit(1);
3114
+ }
3115
+ } catch (error) {
3116
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") console.error(`Error: Path not found: ${args.path}`);
3117
+ else console.error(`Error: ${String(error)}`);
3118
+ process.exit(1);
3119
+ }
3120
+ }
3121
+ });
3122
+ const fillCommand = defineCommand({
3123
+ name: "fill",
3124
+ description: "Fill the values each table computes into the JSONL rows that have none for the named fields",
3125
+ args: z.object({
3126
+ path: arg(z.string(), {
3127
+ positional: true,
3128
+ description: "Data directory, or one .jsonl file in it"
3129
+ }),
3130
+ fields: arg(z.string().optional(), {
3131
+ alias: "f",
3132
+ description: "Comma-separated fields to fill (default: each table's primary key)"
3133
+ })
3134
+ }),
3135
+ run: async (args) => {
3136
+ const fields = args.fields?.split(",").map((field) => field.trim()).filter(Boolean);
3137
+ const result = await fillFields({
3138
+ path: args.path,
3139
+ fields
3140
+ });
3141
+ if (!result.ok) {
3142
+ console.error("Error:", result.error.message);
3143
+ process.exit(1);
3144
+ }
3145
+ const { filled, tablesWithoutSchema, unreadableLines, unproducedFields } = result.value;
3146
+ for (const table of tablesWithoutSchema) console.warn(styleText("yellow", `⚠ No schema file for ${table}, so nothing can be filled in there`));
3147
+ for (const { file, lines } of unreadableLines) console.warn(styleText("yellow", `⚠ ${file}: line(s) ${lines.join(", ")} are not JSON objects, so nothing was filled in there`));
3148
+ if (unproducedFields.length > 0) console.warn(styleText("yellow", `⚠ No table produces a value for: ${unproducedFields.join(", ")}`));
3149
+ if (filled.length === 0) console.log(styleText("green", "✓ Nothing to fill"));
3150
+ for (const { file, fields: written, count } of filled) console.log(styleText("green", `✓ ${file}: filled ${written.join(", ")} in ${count} row(s)`));
3151
+ }
3152
+ });
3153
+ async function loadStudio() {
3154
+ try {
3155
+ return await import("@lines-db/studio");
3156
+ } catch (error) {
3157
+ if (error instanceof Error && "code" in error && error.code === "ERR_MODULE_NOT_FOUND" && error.message.includes("Cannot find package '@lines-db/studio'")) throw new Error("Studio requires @lines-db/studio. Install it with: npm install -D @lines-db/studio");
3158
+ throw error;
3159
+ }
3160
+ }
3161
+ let studio;
3162
+ const studioCommand = defineCommand({
3163
+ name: "studio",
3164
+ description: "Browse and edit the tables of a data directory in the browser",
3165
+ args: z.object({
3166
+ path: arg(z.string().optional(), {
3167
+ positional: true,
3168
+ description: "Directory containing JSONL files"
3169
+ }),
3170
+ dataDir: arg(z.array(z.string()).default([]), { description: "Directory containing JSONL files (repeatable)" }),
3171
+ schemaDir: arg(z.string().optional(), { description: "Directory containing shared schema files (required for several data directories)" }),
3172
+ port: arg(z.coerce.number().int().min(0).max(65535).default(4848), {
3173
+ alias: "p",
3174
+ description: "Port to listen on (0 picks a free one)"
3175
+ }),
3176
+ open: arg(z.boolean().default(false), { description: "Open the studio in the default browser" }),
3177
+ writeFilledValues: arg(z.enum(["all", "primaryKey"]).default("primaryKey"), { description: "Values the schema fills in that a save writes: all of them, or only a generated primary key" })
3178
+ }),
3179
+ run: async (args) => {
3180
+ try {
3181
+ const dataDirs = [...args.path ? [args.path] : [], ...args.dataDir];
3182
+ if (dataDirs.length === 0) throw new Error("Pass a data directory or --data-dir");
3183
+ const { startStudioServer } = await loadStudio();
3184
+ studio = await startStudioServer({
3185
+ dataDir: dataDirs.length === 1 ? dataDirs[0] : dataDirs,
3186
+ schemaDir: args.schemaDir,
3187
+ port: args.port,
3188
+ writeFilledValues: args.writeFilledValues
3189
+ });
3190
+ } catch (error) {
3191
+ console.error("Error:", error instanceof Error ? error.message : String(error));
3192
+ process.exit(1);
3193
+ }
3194
+ console.log(`lines-db studio is running at ${styleText("cyan", studio.url)}`);
3195
+ console.log("Press Ctrl+C to stop.");
3196
+ if (args.open) openInBrowser(studio.url);
3197
+ await new Promise(() => {});
3198
+ },
3199
+ cleanup: async () => {
3200
+ await studio?.close();
3201
+ }
3202
+ });
3203
+ function openInBrowser(url) {
3204
+ const [command, ...commandArgs] = process.platform === "darwin" ? ["open", url] : process.platform === "win32" ? [
3205
+ "cmd",
3206
+ "/c",
3207
+ "start",
3208
+ "\"\"",
3209
+ url
3210
+ ] : ["xdg-open", url];
3211
+ spawn(command, commandArgs, {
3212
+ stdio: "ignore",
3213
+ detached: true
3214
+ }).on("error", () => console.warn(`Could not open a browser; visit ${url}`)).unref();
3215
+ }
3216
+ const program = defineCommand({
3217
+ name: "lines-db",
3218
+ description: "Database utilities for JSONL files",
3219
+ subCommands: {
3220
+ generate: generateCommand,
3221
+ validate: validateCommand,
3222
+ migrate: migrateCommand,
3223
+ fill: fillCommand,
3224
+ studio: studioCommand
3225
+ }
3226
+ });
3227
+ runMain(program, { version: "1.0.0" });
3228
+ /**
3229
+ * Parse the --fields option into the list of fields to write back
3230
+ */
3231
+ function parseWriteBackFields(fields) {
3232
+ if (fields === void 0) return void 0;
3233
+ const parsed = fields.split(",").map((field) => field.trim()).filter((field) => field.length > 0);
3234
+ if (parsed.length === 0) {
3235
+ console.error("Error: --fields must name at least one field");
3236
+ process.exit(1);
3237
+ }
3238
+ return parsed;
3239
+ }
3240
+ /**
3241
+ * Reject fields no loaded table has, so a typo in --fields is not a silent no-op.
3242
+ * A field only some tables have is fine: the tables without it just leave it out.
3243
+ */
3244
+ async function assertWriteBackFieldsExist(db, fields) {
3245
+ if (!fields) return;
3246
+ const known = new Set(db.getTableNames().flatMap((name) => db.getSchema(name)?.columns.map((col) => col.name) ?? []));
3247
+ const unknown = fields.filter((field) => !known.has(field));
3248
+ if (unknown.length > 0) {
3249
+ console.error(`Error: --fields names field(s) no table has: ${unknown.join(", ")}`);
3250
+ await db.close();
3251
+ process.exit(1);
3252
+ }
3253
+ }
3254
+ /**
3255
+ * Migrate all JSONL files in a directory
3256
+ */
3257
+ async function migrateDirectory(dirPath, transformStr, options) {
3258
+ const jsonlFiles = (await readdir(dirPath, { withFileTypes: true })).filter((entry) => entry.isFile() && entry.name.endsWith(".jsonl")).map((entry) => entry.name);
3259
+ if (jsonlFiles.length === 0) {
3260
+ console.error(`Error: No JSONL files found in directory: ${dirPath}`);
3261
+ process.exit(1);
3262
+ }
3263
+ console.log(`Found ${jsonlFiles.length} JSONL file(s) in directory`);
3264
+ const db = LinesDB.create({
3265
+ dataDir: dirPath,
3266
+ writeBackFields: options.writeBackFields
3267
+ });
3268
+ const initResult = unwrap(await db.initialize({ detailedValidate: true }));
3269
+ if (initResult.warnings.length > 0) for (const warning of initResult.warnings) console.warn(styleText("yellow", `⚠ ${warning}`));
3270
+ if (!initResult.valid) {
3271
+ console.error(`Error: Failed to initialize database due to validation errors:`);
3272
+ const formatter = new ErrorFormatter({ verbose: options.verbose });
3273
+ for (const error of initResult.errors) console.error(formatter.formatValidationErrors([{
3274
+ file: error.file,
3275
+ rowIndex: error.rowIndex,
3276
+ issues: error.issues
3277
+ }]));
3278
+ await db.close();
3279
+ process.exit(1);
3280
+ }
3281
+ const tableNames = db.getTableNames();
3282
+ if (tableNames.length === 0) {
3283
+ console.error(`Error: No tables could be loaded from directory: ${dirPath}`);
3284
+ await db.close();
3285
+ process.exit(1);
3286
+ }
3287
+ console.log(`Loaded ${tableNames.length} table(s): ${tableNames.join(", ")}\n`);
3288
+ await assertWriteBackFieldsExist(db, options.writeBackFields);
3289
+ try {
3290
+ const transform = runInSandbox(`(${transformStr})`);
3291
+ if (typeof transform !== "function") {
3292
+ console.error("Error: Transform must be a function");
3293
+ await db.close();
3294
+ process.exit(1);
3295
+ }
3296
+ let filter = void 0;
3297
+ if (options.filter) try {
3298
+ filter = JSON.parse(options.filter);
3299
+ } catch {
3300
+ filter = runInSandbox(`(${options.filter})`);
3301
+ }
3302
+ let totalRowsMigrated = 0;
3303
+ let hasErrors = false;
3304
+ for (const tableName of tableNames) try {
3305
+ console.log(`Processing table '${tableName}'...`);
3306
+ const rowsToMigrate = unwrap(filter ? db.find(tableName, filter) : db.find(tableName));
3307
+ if (rowsToMigrate.length === 0) {
3308
+ console.log(` No rows to migrate`);
3309
+ continue;
3310
+ }
3311
+ console.log(` Found ${rowsToMigrate.length} row(s) to migrate`);
3312
+ const transformedRows = rowsToMigrate.map((row) => transform(row));
3313
+ unwrap(await db.transaction(async (tx) => {
3314
+ unwrap(tx.batchUpdate(tableName, transformedRows, { validate: true }));
3315
+ }));
3316
+ console.log(` ✓ ${rowsToMigrate.length} row(s) updated\n`);
3317
+ totalRowsMigrated += rowsToMigrate.length;
3318
+ } catch (error) {
3319
+ hasErrors = true;
3320
+ console.error(styleText("red", ` ✗ Failed to migrate table '${tableName}'`));
3321
+ const formatter = new ErrorFormatter({ verbose: options.verbose });
3322
+ if (error instanceof Error && error.name === "ValidationError") {
3323
+ const validationError = error;
3324
+ if (validationError.validationErrors) {
3325
+ console.error(` Found ${validationError.validationErrors.length} validation error(s):\n`);
3326
+ const rowsToMigrate = unwrap(filter ? db.find(tableName, filter) : db.find(tableName));
3327
+ const errorInfos = validationError.validationErrors.map(({ rowIndex, rowData, error: rowError }) => ({
3328
+ file: join(dirPath, `${tableName}.jsonl`),
3329
+ rowIndex,
3330
+ issues: rowError.issues,
3331
+ data: rowData,
3332
+ originalData: rowsToMigrate[rowIndex]
3333
+ }));
3334
+ const formatted = formatter.formatValidationErrors(errorInfos);
3335
+ console.error(formatted);
3336
+ }
3337
+ } else if (error instanceof Error) console.error(` ${error.message}`);
3338
+ console.error("");
3339
+ }
3340
+ unwrap(await db.close());
3341
+ if (hasErrors) {
3342
+ console.error(styleText("red", `\n✗ Migration completed with errors for some tables`));
3343
+ console.log(`Total rows migrated: ${totalRowsMigrated}`);
3344
+ process.exit(1);
3345
+ } else {
3346
+ console.log(styleText("green", `\n✓ Migration completed successfully for all tables`));
3347
+ console.log(`Total rows migrated: ${totalRowsMigrated}`);
3348
+ process.exit(0);
3349
+ }
3350
+ } catch (error) {
3351
+ await db.close();
3352
+ throw error;
3353
+ }
3354
+ }
3355
+ /**
3356
+ * Migrate a single JSONL file
3357
+ */
3358
+ async function migrateFile(filePath, transformStr, options) {
3359
+ const tableName = basename(filePath, ".jsonl");
3360
+ if (!tableName) {
3361
+ console.error("Error: Invalid file path. Must be a .jsonl file");
3362
+ process.exit(1);
3363
+ }
3364
+ const dataDir = dirname(filePath);
3365
+ let transform;
3366
+ try {
3367
+ const parsedTransform = runInSandbox(`(${transformStr})`);
3368
+ if (typeof parsedTransform !== "function") {
3369
+ console.error("Error: Transform must be a function");
3370
+ process.exit(1);
3371
+ }
3372
+ transform = parsedTransform;
3373
+ } catch (error) {
3374
+ console.error("Error: Failed to parse transform function");
3375
+ console.error(` ${error instanceof Error ? error.message : String(error)}`);
3376
+ process.exit(1);
3377
+ }
3378
+ const db = LinesDB.create({
3379
+ dataDir,
3380
+ writeBackFields: options.writeBackFields
3381
+ });
3382
+ const initResult = unwrap(await db.initialize({
3383
+ tableName,
3384
+ transform,
3385
+ detailedValidate: true
3386
+ }));
3387
+ if (initResult.warnings.length > 0) for (const warning of initResult.warnings) console.warn(styleText("yellow", `⚠ ${warning}`));
3388
+ if (!initResult.valid) {
3389
+ console.error(`Error: Failed to initialize database due to validation errors:`);
3390
+ const formatter = new ErrorFormatter({ verbose: options.verbose });
3391
+ for (const error of initResult.errors) console.error(formatter.formatValidationErrors([{
3392
+ file: error.file,
3393
+ rowIndex: error.rowIndex,
3394
+ issues: error.issues
3395
+ }]));
3396
+ await db.close();
3397
+ process.exit(1);
3398
+ }
3399
+ await assertWriteBackFieldsExist(db, options.writeBackFields);
3400
+ try {
3401
+ let filter = void 0;
3402
+ if (options.filter) try {
3403
+ filter = JSON.parse(options.filter);
3404
+ } catch {
3405
+ filter = runInSandbox(`(${options.filter})`);
3406
+ }
3407
+ if (filter) {
3408
+ let rowsToMigrate;
3409
+ try {
3410
+ rowsToMigrate = unwrap(db.find(tableName, filter));
3411
+ } catch (error) {
3412
+ console.error(`Error: Failed to access table '${tableName}'`);
3413
+ console.error(` ${error instanceof Error ? error.message : String(error)}`);
3414
+ console.error(`\nThe table may have failed to load during initialization.`);
3415
+ console.error(`Check the table's data and schema for any constraint violations.`);
3416
+ await db.close();
3417
+ process.exit(1);
3418
+ }
3419
+ console.log(`Found ${rowsToMigrate.length} row(s) to migrate in table '${tableName}'`);
3420
+ if (rowsToMigrate.length === 0) {
3421
+ console.log("No rows to migrate. Exiting.");
3422
+ unwrap(await db.close());
3423
+ process.exit(0);
3424
+ }
3425
+ const transformedRows = rowsToMigrate.map((row) => transform(row));
3426
+ try {
3427
+ unwrap(await db.transaction(async (tx) => {
3428
+ unwrap(tx.batchUpdate(tableName, transformedRows, { validate: true }));
3429
+ }));
3430
+ unwrap(await db.close());
3431
+ console.log(`\nMigration completed successfully:`);
3432
+ console.log(` ✓ ${rowsToMigrate.length} row(s) updated`);
3433
+ process.exit(0);
3434
+ } catch (error) {
3435
+ await db.close();
3436
+ if (options.errorOutput) try {
3437
+ const jsonlContent = transformedRows.map((row) => JSON.stringify(row)).join("\n");
3438
+ await writeFile(options.errorOutput, jsonlContent, "utf-8");
3439
+ console.error(styleText("yellow", `\n⚠ Transformed data (${transformedRows.length} rows) written to: ${options.errorOutput}`));
3440
+ } catch (writeError) {
3441
+ console.error(styleText("red", `\n✗ Failed to write error output file: ${writeError instanceof Error ? writeError.message : String(writeError)}`));
3442
+ }
3443
+ const formatter = new ErrorFormatter({ verbose: options.verbose });
3444
+ console.error(formatter.formatMigrationFailureHeader());
3445
+ if (error instanceof Error && error.name === "ValidationError") {
3446
+ const validationError = error;
3447
+ if (validationError.validationErrors) {
3448
+ console.error(`\nFound ${validationError.validationErrors.length} validation error(s) in transformed data:\n`);
3449
+ const errorInfos = validationError.validationErrors.map(({ rowIndex, rowData, error: rowError }) => ({
3450
+ file: filePath,
3451
+ rowIndex,
3452
+ issues: rowError.issues,
3453
+ data: rowData,
3454
+ originalData: rowsToMigrate[rowIndex]
3455
+ }));
3456
+ const formatted = formatter.formatValidationErrors(errorInfos);
3457
+ console.error(formatted);
3458
+ } else {
3459
+ console.error("\nValidation error:\n");
3460
+ const errorInfo = {
3461
+ file: filePath,
3462
+ rowIndex: 0,
3463
+ issues: validationError.issues
3464
+ };
3465
+ const formatted = formatter.formatValidationErrors([errorInfo]);
3466
+ console.error(formatted);
3467
+ }
3468
+ } else if (error instanceof Error) {
3469
+ console.error(`\n ${error.message}`);
3470
+ if (options.verbose && error.stack) console.error(`\nStack trace:\n${error.stack}`);
3471
+ if (error.message.includes("UNIQUE constraint failed") || error.message.includes("FOREIGN KEY constraint failed") || error.message.includes("NOT NULL constraint failed") || error.message.includes("CHECK constraint failed")) {
3472
+ console.error("\n This is a SQLite constraint violation.");
3473
+ console.error(" Please check your data and schema requirements.");
3474
+ }
3475
+ } else console.error(`\n ${String(error)}`);
3476
+ console.error("");
3477
+ process.exit(1);
3478
+ }
3479
+ } else try {
3480
+ const allRows = unwrap(db.find(tableName));
3481
+ console.log(`Migrated ${allRows.length} row(s) in table '${tableName}'`);
3482
+ unwrap(await db.sync(tableName));
3483
+ unwrap(await db.close());
3484
+ console.log(`\nMigration completed successfully:`);
3485
+ console.log(` ✓ ${allRows.length} row(s) updated`);
3486
+ process.exit(0);
3487
+ } catch (error) {
3488
+ await db.close();
3489
+ console.error("Error: Failed to sync changes to file");
3490
+ console.error(` ${error instanceof Error ? error.message : String(error)}`);
3491
+ process.exit(1);
3492
+ }
3493
+ } catch (error) {
3494
+ await db.close();
3495
+ throw error;
3496
+ }
3497
+ }
3498
+ //#endregion
3499
+ export {};