lines-db 0.19.0 → 0.19.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["schema"],"sources":["../src/runtime.ts","../src/sqlite-adapter.ts","../src/jsonl-writer.ts","../src/schema-extensions.ts","../src/schema-loader.ts","../src/directory-scanner.ts","../src/schema.ts","../src/merge-fields.ts","../src/sql-statements.ts","../src/database.ts","../src/fill.ts","../src/type-generator.ts","../src/jsonl-migration.ts","../src/error-formatter.ts","../src/dataset-config.ts"],"sourcesContent":["/**\n * Runtime detection utilities\n */\n\nexport type RuntimeEnvironment = 'node' | 'unknown';\n\nexport function detectRuntime(): RuntimeEnvironment {\n // Check for Node.js\n if (typeof process !== 'undefined' && process.versions && process.versions.node) {\n return 'node';\n }\n\n return 'unknown';\n}\n\nexport const RUNTIME = detectRuntime();\n","/**\n * SQLite adapter for Node.js\n */\n\nimport { RUNTIME } from './runtime.js';\n\n/**\n * Common interface for SQLite database\n */\nexport interface SQLiteDatabase {\n prepare(sql: string): SQLiteStatement;\n exec(sql: string): void;\n close(): void;\n}\n\nexport interface SQLiteStatement {\n run(...params: any[]): { changes: number; lastInsertRowid: number | bigint };\n get(...params: any[]): any;\n all(...params: any[]): any[];\n}\n\n/**\n * Create a SQLite database instance for Node.js\n */\nexport function createDatabase(path: string = ':memory:'): SQLiteDatabase {\n if (RUNTIME === 'node') {\n return createNodeDatabase(path);\n } else {\n throw new Error(`Unsupported runtime: ${RUNTIME}`);\n }\n}\n\n/**\n * Create a Node.js SQLite database\n */\nfunction createNodeDatabase(path: string): SQLiteDatabase {\n // Dynamic import for Node.js\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { DatabaseSync } = require('node:sqlite');\n const db = new DatabaseSync(path);\n\n // CRITICAL: Enable foreign key constraints\n // SQLite disables foreign keys by default, which is a major data integrity issue\n db.exec('PRAGMA foreign_keys = ON');\n\n return {\n prepare(sql: string): SQLiteStatement {\n const stmt = db.prepare(sql);\n return {\n run(...params: any[]) {\n return stmt.run(...params);\n },\n get(...params: any[]) {\n return stmt.get(...params);\n },\n all(...params: any[]) {\n return stmt.all(...params);\n },\n };\n },\n exec(sql: string): void {\n db.exec(sql);\n },\n close(): void {\n db.close();\n },\n };\n}\n","import { writeFile } from 'node:fs/promises';\nimport type { JsonObject } from './types.js';\n\nexport class JsonlWriter {\n /**\n * Write data to JSONL file\n */\n static async write(filePath: string, data: JsonObject[]): Promise<void> {\n await writeFile(filePath, this.serialize(data), 'utf-8');\n }\n\n /**\n * The content {@link write} writes for the data\n */\n static serialize(data: JsonObject[]): string {\n return data.map((obj) => JSON.stringify(obj)).join('\\n') + '\\n';\n }\n\n /**\n * Append data to JSONL file\n */\n static async append(filePath: string, data: JsonObject[]): Promise<void> {\n const { readFile, writeFile } = await import('node:fs/promises');\n\n try {\n const existing = await readFile(filePath, 'utf-8');\n const lines = data.map((obj) => JSON.stringify(obj)).join('\\n');\n const newContent = existing.trim() + '\\n' + lines + '\\n';\n await writeFile(filePath, newContent, 'utf-8');\n } catch (error) {\n // If file doesn't exist, just write the data\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n await this.write(filePath, data);\n } else {\n throw error;\n }\n }\n }\n}\n","import { access } from 'node:fs/promises';\nimport { join } from 'node:path';\n\n/**\n * Supported schema file extensions, in priority order.\n * The first match wins when discovering schema files.\n */\nexport const SCHEMA_EXTENSIONS = ['.schema.ts', '.schema.mts', '.schema.cts'] as const;\nexport type SchemaExtension = (typeof SCHEMA_EXTENSIONS)[number];\n\n/**\n * Map from schema extensions to their JavaScript import counterparts.\n */\nconst SCHEMA_TO_JS_IMPORT_MAP: Record<string, string> = {\n '.schema.ts': '.schema.js',\n '.schema.mts': '.schema.mjs',\n '.schema.cts': '.schema.cjs',\n};\n\n/**\n * Try each supported schema extension and return the full path of the first\n * one that exists on disk. Returns undefined if none is found.\n */\nexport async function findSchemaFile(dir: string, tableName: string): Promise<string | undefined> {\n for (const ext of SCHEMA_EXTENSIONS) {\n const candidate = join(dir, `${tableName}${ext}`);\n try {\n await access(candidate);\n return candidate;\n } catch {\n // Continue to next extension\n }\n }\n return undefined;\n}\n\n/**\n * Synchronously find a schema file among directory entries.\n * Returns the full path of the first match, or undefined.\n */\nexport function findSchemaFileInEntries(\n dataDirPath: string,\n tableName: string,\n entries: { isFile(): boolean; name: string }[],\n): string | undefined {\n for (const ext of SCHEMA_EXTENSIONS) {\n const candidateName = `${tableName}${ext}`;\n if (entries.some((e) => e.isFile() && e.name === candidateName)) {\n return join(dataDirPath, candidateName);\n }\n }\n return undefined;\n}\n\n/**\n * Check if a filename matches any supported schema file pattern.\n */\nexport function isSchemaFile(fileName: string): boolean {\n return SCHEMA_EXTENSIONS.some((ext) => fileName.endsWith(ext));\n}\n\n/**\n * Extract table name from a schema filename.\n * e.g., \"users.schema.ts\" -> \"users\", \"users.schema.mts\" -> \"users\"\n */\nexport function extractTableNameFromSchemaFile(fileName: string): string | null {\n for (const ext of SCHEMA_EXTENSIONS) {\n if (fileName.endsWith(ext)) {\n return fileName.slice(0, -ext.length);\n }\n }\n return null;\n}\n\n/**\n * Rewrite a TypeScript path to its JavaScript counterpart for ESM imports.\n * \".schema.ts\" -> \".schema.js\", \".schema.mts\" -> \".schema.mjs\", \".schema.cts\" -> \".schema.cjs\"\n */\nexport function rewriteExtensionForImport(filePath: string): string {\n for (const [tsExt, jsExt] of Object.entries(SCHEMA_TO_JS_IMPORT_MAP)) {\n if (filePath.endsWith(tsExt)) {\n return filePath.slice(0, -tsExt.length) + jsExt;\n }\n }\n return filePath;\n}\n","import { pathToFileURL } from 'node:url';\nimport { dirname, basename } from 'node:path';\nimport type { StandardSchema } from './types.js';\nimport { findSchemaFile, SCHEMA_EXTENSIONS } from './schema-extensions.js';\n\nexport class SchemaLoader {\n /**\n * Check if a schema file exists for a table\n */\n static async hasSchema(jsonlPath: string, schemaDir?: string): Promise<boolean> {\n const dir = schemaDir ?? dirname(jsonlPath);\n const tableName = basename(jsonlPath, '.jsonl');\n const schemaPath = await findSchemaFile(dir, tableName);\n return schemaPath !== undefined;\n }\n\n /**\n * Load a validation schema file for a table\n * Requires ${tableName}.schema.{ts,mts,cts} to exist in schemaDir, or alongside the JSONL file when omitted\n */\n static async loadSchema(jsonlPath: string, schemaDir?: string): Promise<StandardSchema> {\n const dir = schemaDir ?? dirname(jsonlPath);\n const tableName = basename(jsonlPath, '.jsonl');\n const schemaPath = await findSchemaFile(dir, tableName);\n\n if (!schemaPath) {\n throw new Error(\n `Schema file not found for table '${tableName}'. Expected one of: ${SCHEMA_EXTENSIONS.map((ext) => `${tableName}${ext}`).join(', ')}`,\n );\n }\n\n try {\n const schemaUrl = pathToFileURL(schemaPath).href;\n // Add cache busting query parameter to force reload on each import\n // This ensures schema changes are picked up immediately\n const cacheBustedUrl = `${schemaUrl}?t=${Date.now()}`;\n const module = await import(cacheBustedUrl);\n const schema = module.default || module.schema;\n\n if (schema && this.isStandardSchema(schema)) {\n return schema;\n }\n\n throw new Error(`Schema file ${schemaPath} does not export a valid StandardSchema`);\n } catch (error) {\n throw new Error(\n `Failed to load schema for table '${tableName}' from ${schemaPath}: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error instanceof Error ? error : undefined },\n );\n }\n }\n\n /**\n * Check if an object implements the StandardSchema interface\n */\n private static isStandardSchema(obj: unknown): obj is StandardSchema {\n if (!obj || typeof obj !== 'object') return false;\n\n const schema = obj as Record<string, unknown>;\n const standard = schema['~standard'];\n\n if (!standard || typeof standard !== 'object') return false;\n\n const standardObj = standard as Record<string, unknown>;\n\n return (\n standardObj.version === 1 && typeof standardObj.vendor === 'string' && typeof standardObj.validate === 'function'\n );\n }\n}\n","import { readdir } from 'node:fs/promises';\nimport { join, basename, extname } from 'node:path';\nimport type { TableConfig } from './types.js';\n\nexport class DirectoryScanner {\n /**\n * Scan directories for JSONL files and create table configurations.\n * A table found in several directories lists its files in the order the directories are given.\n */\n static async scanDirectory(dataDir: string | readonly string[]): Promise<Map<string, TableConfig>> {\n const dataDirs = typeof dataDir === 'string' ? [dataDir] : dataDir;\n const jsonlPathsByTable = new Map<string, string[]>();\n\n for (const dir of dataDirs) {\n let files: string[];\n try {\n files = await readdir(dir);\n } catch (error) {\n throw new Error(`Failed to scan directory ${dir}: ${error instanceof Error ? error.message : String(error)}`);\n }\n\n for (const file of files) {\n if (extname(file) === '.jsonl') {\n const tableName = basename(file, '.jsonl');\n const jsonlPaths = jsonlPathsByTable.get(tableName) ?? [];\n jsonlPaths.push(join(dir, file));\n jsonlPathsByTable.set(tableName, jsonlPaths);\n }\n }\n }\n\n if (jsonlPathsByTable.size === 0) {\n console.warn(`Warning: No JSONL files found in directory: ${dataDirs.join(', ')}`);\n }\n\n const tables = new Map<string, TableConfig>();\n for (const [tableName, jsonlPaths] of jsonlPathsByTable) {\n tables.set(tableName, { jsonlPath: jsonlPaths[0], jsonlPaths, autoInferSchema: true });\n }\n return tables;\n }\n}\n","import type { StandardSchema, Table, ForeignKeyDefinition, IndexDefinition } from './types.js';\n\n/**\n * Schema options for defining constraints and indexes\n * When Input and Output types differ, backward transformation is required\n */\nexport type SchemaOptions<Input extends Table, Output extends Table> = {\n /**\n * Primary key column\n */\n primaryKey?: string;\n\n /**\n * Foreign key constraints\n */\n foreignKeys?: ForeignKeyDefinition[];\n\n /**\n * Indexes to create\n */\n indexes?: IndexDefinition[];\n} & (Output extends Input\n ? {\n /**\n * Backward transformation from Output to Input (optional when output is substitutable for input)\n */\n backward?: (output: Output) => Input;\n }\n : {\n /**\n * Backward transformation from Output to Input (REQUIRED when types differ)\n */\n backward: (output: Output) => Input;\n });\n\n/**\n * BiDirectional Schema interface\n * Extends StandardSchema with optional backward transformation and schema metadata\n */\nexport interface BiDirectionalSchema<Input extends Table = Table, Output extends Table = Input> extends StandardSchema<\n Input,\n Output\n> {\n /**\n * Backward transformation from Output to Input\n * Required when Input and Output types differ (e.g., with transformations)\n */\n backward?: (output: Output) => Input;\n\n /**\n * Primary key column\n */\n primaryKey?: string;\n\n /**\n * Foreign key constraints\n */\n foreignKeys?: ForeignKeyDefinition[];\n\n /**\n * Indexes to create\n */\n indexes?: IndexDefinition[];\n}\n\n/**\n * Define a bidirectional schema with optional backward transformation\n *\n * @param schema - Standard Schema for validation\n * @param options - SchemaOptions object. When Input and Output types differ, backward transformation is required\n *\n * @example\n * // No transformation - backward not needed\n * const schema = defineSchema(\n * v.object({ id: v.number(), name: v.string() })\n * );\n *\n * @example\n * // With transformation - backward REQUIRED\n * const schema = defineSchema(\n * v.pipe(v.string(), v.transform(Number)),\n * {\n * backward: (num) => String(num) // backward: number → string (REQUIRED)\n * }\n * );\n *\n * @example\n * // With primary key and foreign key\n * const schema = defineSchema(\n * v.object({ id: v.number(), customerId: v.number() }),\n * {\n * primaryKey: 'id',\n * foreignKeys: [\n * { column: 'customerId', references: { table: 'users', column: 'id' } }\n * ]\n * }\n * );\n */\nexport function defineSchema<Input extends Table, Output extends Table>(\n schema: StandardSchema<Input, Output>,\n ...args: Output extends Input ? [options?: SchemaOptions<Input, Output>] : [options: SchemaOptions<Input, Output>]\n): BiDirectionalSchema<Input, Output> {\n const options = args[0];\n // Create a new object that extends the schema\n const bidirectionalSchema = Object.create(schema) as BiDirectionalSchema<Input, Output>;\n\n // Handle options object\n if (options) {\n if (options.backward) {\n bidirectionalSchema.backward = options.backward as (output: Output) => Input;\n }\n if (options.primaryKey) {\n bidirectionalSchema.primaryKey = options.primaryKey;\n }\n if (options.foreignKeys) {\n bidirectionalSchema.foreignKeys = options.foreignKeys;\n }\n if (options.indexes) {\n bidirectionalSchema.indexes = options.indexes;\n }\n }\n\n // Copy '~standard' property\n Object.defineProperty(bidirectionalSchema, '~standard', {\n value: schema['~standard'],\n enumerable: true,\n configurable: true,\n });\n\n return bidirectionalSchema;\n}\n\n/**\n * Check if a schema has backward transformation\n */\nexport function hasBackward<Input extends Table, Output extends Table>(\n schema: StandardSchema<Input, Output>,\n): schema is BiDirectionalSchema<Input, Output> {\n return 'backward' in schema && typeof (schema as { backward?: unknown }).backward === 'function';\n}\n","import type { JsonObject, JsonValue } from './types.js';\n\n/**\n * Options for {@link mergeFields}\n */\nexport interface MergeFieldsOptions {\n /**\n * Fields taken from the computed row. Every other field keeps the value the line holds.\n * A field the computed row has no value for is not written, so the line keeps what it has rather\n * than having a null written over it.\n */\n fields: readonly string[];\n\n /**\n * The order fields are declared in, used to place a field the line did not have.\n * Defaults to the order the computed row lists its own fields in - a row a schema computed lists\n * them the way that schema declares them.\n */\n keyOrder?: Iterable<string>;\n}\n\n/**\n * Lay the named fields of a computed row over the line a JSONL file already holds.\n *\n * A field the line did not have is inserted where the schema declares it rather than appended, so a\n * filled-in `id` lands at the front of the line the way a hand-written row has it. No key the line\n * already had moves, and a key the schema does not declare stays behind the declared ones.\n *\n * @param line - The row as the JSONL file holds it\n * @param computed - The row a schema computed from it, which the named fields are taken from. Only its\n * own fields count: a field the schema does not produce is left to the line even when a name like\n * `toString` would resolve to something on `Object.prototype`. A field it holds as `undefined` is\n * left to the line as well.\n * @param options - The fields to take, and the order they are declared in\n * @returns A new row: the line, with the named fields written into it\n *\n * @example\n * // line: {\"name\":\"Alice\",\"note\":\"check\"}\n * // computed: {\"id\":\"018f…\",\"name\":\"Alice\",\"createdAt\":\"2026-…\"}\n * mergeFields(line, computed, { fields: ['id', 'createdAt'] });\n * // {\"id\":\"018f…\",\"name\":\"Alice\",\"createdAt\":\"2026-…\",\"note\":\"check\"}\n */\nexport function mergeFields(\n line: JsonObject,\n computed: Record<string, JsonValue | undefined>,\n options: MergeFieldsOptions,\n): JsonObject {\n const rank = new Map<string, number>();\n for (const key of options.keyOrder ?? Object.keys(computed)) {\n // The first mention wins, so a key the order lists twice keeps its earliest place\n if (!rank.has(key)) {\n rank.set(key, rank.size);\n }\n }\n // A key the schema does not declare ranks past every declared one, and so keeps its place\n const rankOf = (key: string): number => rank.get(key) ?? Number.MAX_SAFE_INTEGER;\n\n const written = new Map<string, JsonValue>();\n for (const field of options.fields) {\n // `Object.hasOwn`, not a check on the value: a field named `toString` would otherwise take what\n // `Object.prototype` holds. A field the computed row has as undefined is left to the line too,\n // since writing undefined would drop the key entirely\n if (Object.hasOwn(computed, field) && computed[field] !== undefined) {\n written.set(field, computed[field]);\n }\n }\n\n // `Object.hasOwn`, not `field in line`: a field named `toString` would otherwise read as present\n const inserted = Array.from(written.keys())\n .filter((field) => !Object.hasOwn(line, field))\n .sort((a, b) => rankOf(a) - rankOf(b));\n\n const entries: [string, JsonValue][] = [];\n for (const key of Object.keys(line)) {\n while (inserted.length > 0 && rankOf(inserted[0]) < rankOf(key)) {\n const field = inserted.shift()!;\n entries.push([field, written.get(field)!]);\n }\n entries.push([key, written.has(key) ? written.get(key)! : line[key]]);\n }\n for (const field of inserted) {\n entries.push([field, written.get(field)!]);\n }\n\n // Not an object literal with assignments: a line holding `__proto__` or `toString` keeps that key\n return Object.fromEntries(entries);\n}\n\n/**\n * The row with the fields its line holds that the table has no column for - a schema that strips\n * unknown keys lets them through - kept where the line holds them, so writing back does not drop them\n */\nexport function keepUnknownFields(line: JsonObject, row: JsonObject, columns: ReadonlySet<string>): JsonObject {\n const unknown = Object.keys(line).filter((key) => !columns.has(key) && !Object.hasOwn(row, key));\n if (unknown.length === 0) return row;\n const entries: Array<[string, JsonValue]> = [];\n for (const key of Object.keys(line)) {\n if (Object.hasOwn(row, key)) entries.push([key, row[key]]);\n else if (unknown.includes(key)) entries.push([key, line[key]]);\n }\n for (const key of Object.keys(row)) if (!Object.hasOwn(line, key)) entries.push([key, row[key]]);\n // Not assigned to an object literal: a key named `__proto__` would set the prototype instead\n return Object.fromEntries(entries);\n}\n","const TRIGGER_DEFINITION = /^\\s*CREATE\\s+(?:TEMP(?:ORARY)?\\s+)?TRIGGER\\b/i;\nconst CLOSER: Record<string, string> = { \"'\": \"'\", '\"': '\"', '`': '`', '[': ']' };\n\n/**\n * Split SQL text into its statements at `;`, the way SQLite reads it: a `;` inside a comment or quoted\n * text does not end a statement, and a comment is left out as the whitespace it is\n */\nexport function splitStatements(sql: string): string[] {\n const statements: string[] = [];\n let current = '';\n let i = 0;\n while (i < sql.length) {\n const char = sql[i]!;\n if (char === '-' && sql[i + 1] === '-') {\n const end = sql.indexOf('\\n', i);\n i = end === -1 ? sql.length : end;\n current += ' ';\n } else if (char === '/' && sql[i + 1] === '*') {\n const end = sql.indexOf('*/', i + 2);\n i = end === -1 ? sql.length : end + 2;\n current += ' ';\n } else if (char in CLOSER) {\n // A doubled quote inside is read as a closing one followed by an opening one, which copies the same\n const end = sql.indexOf(CLOSER[char]!, i + 1);\n const stop = end === -1 ? sql.length : end + 1;\n current += sql.slice(i, stop);\n i = stop;\n } else if (char === ';' && !insideTriggerBody(current)) {\n statements.push(current);\n current = '';\n i += 1;\n } else {\n current += char;\n i += 1;\n }\n }\n statements.push(current);\n return statements.map((statement) => statement.trim()).filter((statement) => statement.length > 0);\n}\n\n/**\n * Whether a `;` after this text is inside the body of a trigger, which only a `;` followed by `END` and\n * another `;` closes. Only an END right after a `;` counts, as the END of a CASE in the body does not\n */\nfunction insideTriggerBody(statement: string): boolean {\n return TRIGGER_DEFINITION.test(statement) && !/;\\s*END$/i.test(statement.trimEnd());\n}\n\nconst READ_STATEMENTS = new Set(['SELECT', 'VALUES', 'WITH', 'EXPLAIN']);\n\n// A pragma that takes an argument and only reads: PRAGMA table_info(tags)\nconst READ_PRAGMAS_WITH_ARGUMENT = new Set([\n 'table_info',\n 'table_xinfo',\n 'table_list',\n 'index_list',\n 'index_info',\n 'index_xinfo',\n 'foreign_key_list',\n 'foreign_key_check',\n 'integrity_check',\n 'quick_check',\n 'collation_list',\n 'database_list',\n 'function_list',\n 'module_list',\n 'pragma_list',\n 'compile_options',\n]);\n\n// A pragma that reads when bare and sets when given a value or an argument: PRAGMA user_version(5) sets it\nconst READ_PRAGMAS_BARE = new Set([\n 'query_only',\n 'user_version',\n 'application_id',\n 'schema_version',\n 'foreign_keys',\n 'journal_mode',\n 'page_count',\n 'page_size',\n 'freelist_count',\n 'encoding',\n 'data_version',\n]);\n\nconst PRAGMA_NAME = String.raw`(?:\\w+|\"[^\"]*\"|'[^']*'|\\x60[^\\x60]*\\x60|\\[[^\\]]*\\])`;\nconst PRAGMA_STATEMENT = new RegExp(\n String.raw`^PRAGMA\\s+(?:${PRAGMA_NAME}\\s*\\.\\s*)?(${PRAGMA_NAME})\\s*(\\(.*\\))?$`,\n 'is',\n);\n\n/**\n * Whether a statement, as {@link splitStatements} returns it, only reads. Closed by default: whatever is\n * not known to read is refused, so a statement or pragma added to SQLite later is refused too. A WITH\n * can wrap a write, which the read-only mode of the connection is left to refuse\n */\nexport function isReadOnlyStatement(statement: string): boolean {\n const keyword = /^[A-Za-z]+/.exec(statement)?.[0]?.toUpperCase();\n if (keyword === undefined) return false;\n if (READ_STATEMENTS.has(keyword)) return true;\n if (keyword !== 'PRAGMA') return false;\n\n const match = PRAGMA_STATEMENT.exec(statement);\n if (!match) return false;\n const name = match[1]!.replace(/^[\"'`[]|[\"'`\\]]$/g, '').toLowerCase();\n const argument = match[2];\n if (READ_PRAGMAS_WITH_ARGUMENT.has(name)) return true;\n return READ_PRAGMAS_BARE.has(name) && argument === undefined;\n}\n","import { createDatabase, type SQLiteDatabase } from './sqlite-adapter.js';\nimport { JsonlReader, hashJsonlContent } from './jsonl-reader.js';\nimport { JsonlWriter } from './jsonl-writer.js';\nimport { replaceFile } from './replace-file.js';\nimport { SchemaLoader } from './schema-loader.js';\nimport { DirectoryScanner } from './directory-scanner.js';\nimport { hasBackward } from './schema.js';\nimport { keepUnknownFields, mergeFields } from './merge-fields.js';\nimport { findSchemaFile } from './schema-extensions.js';\nimport { readFile, rm, writeFile } from 'node:fs/promises';\nimport { randomBytes } from 'node:crypto';\nimport { dirname, join, resolve } from 'node:path';\nimport type {\n DatabaseConfig,\n TableSchema,\n ColumnDefinition,\n JsonObject,\n TableConfig,\n StandardSchema,\n ValidationError,\n JsonlConflictError,\n Table,\n TableDefs,\n WriteFilledValues,\n WhereCondition,\n ValidationResult,\n ValidationErrorDetail,\n TableValidationResult,\n ForeignKeyDefinition,\n} from './types.js';\nimport type { BiDirectionalSchema } from './schema.js';\nimport { type Result, ok, err, toError, unwrap } from './result.js';\nimport { isReadOnlyStatement, splitStatements } from './sql-statements.js';\n\n/**\n * Options for {@link LinesDB.update}\n */\nexport interface UpdateOptions {\n /** Validate each updated row against the table's schema. Defaults to true */\n validate?: boolean;\n /**\n * Fields to leave to the schema: each updated row stores the value its schema fills in for them, and\n * a write-back removes them from the row's line\n */\n resetToDefault?: readonly string[];\n}\n\n/**\n * Options for {@link LinesDB.sync}\n */\nexport interface SyncOptions {\n /**\n * Fields written back to the JSONL file.\n * When provided, only these fields are taken from the database and merged into the matching\n * JSONL line; every other field keeps the value the file already had. An empty list takes no\n * field from the database, so existing lines keep every value they hold - rows added to or\n * removed from the database are still reflected.\n * Defaults to `writeBackFields` from the database config, or writing every field of the row.\n */\n fields?: readonly string[];\n /**\n * Which values the validation schema fills in to write into the file.\n * Defaults to `writeFilledValues` from the database config, or `'all'`.\n */\n writeFilledValues?: WriteFilledValues;\n}\n\n/**\n * Sync options plus how to treat fields a table does not have: a sync asked for one table by name\n * rejects them, while a sync covering every table just leaves them out.\n */\ntype InternalSyncOptions = SyncOptions & { strictFields?: boolean };\n\n/** The rows a table is about to be written back as, and what its file held before */\ninterface PreparedWriteBack {\n tableName: string;\n jsonlPath: string;\n rows: JsonObject[];\n /** Undefined when the file did not exist */\n previousContent: string | undefined;\n /** How many changes the table had seen when its rows were read */\n generation: number;\n rowids?: string[];\n unchanged?: boolean;\n completed?: boolean;\n}\n\n/** The fields set and reset on a row since its table was last written back */\ninterface FieldChanges {\n set: Set<string>;\n reset: Set<string>;\n /** Whether the row was inserted, rather than read from a line */\n inserted: boolean;\n}\n\nfunction cloneFieldChanges(changes: Map<string, Map<string, FieldChanges>>): Map<string, Map<string, FieldChanges>> {\n return new Map(\n Array.from(changes, ([tableName, byRow]) => [\n tableName,\n new Map(\n Array.from(byRow, ([rowid, row]) => [\n rowid,\n { set: new Set(row.set), reset: new Set(row.reset), inserted: row.inserted },\n ]),\n ),\n ]),\n );\n}\n\n/** Column alias a query reads a row's rowid under, next to its fields */\nconst ROWID_ALIAS = '__lines_db_rowid';\n\n/** The fields a row given to an insert names, leaving out those it leaves undefined */\nfunction givenFields(row: object): string[] {\n return Object.entries(row)\n .filter(([, value]) => value !== undefined)\n .map(([key]) => key);\n}\n\n/** Whether a value read from SQLite and one about to be stored are the same */\nfunction sameStoredValue(stored: unknown, next: unknown): boolean {\n if (stored === null || stored === undefined || next === null) return (stored ?? null) === next;\n return String(stored) === String(next);\n}\n\n/** The JSONL file a row was read from, and its index among that file's rows */\ninterface RowOrigin {\n file: string;\n rowIndex: number;\n}\n\nexport class LinesDB<Tables extends TableDefs> {\n private db: SQLiteDatabase;\n private readonly rowMovesTable = `__lines_db_moves_${randomBytes(12).toString('hex')}`;\n private config: DatabaseConfig<Tables>;\n private schemas: Map<string, TableSchema> = new Map();\n private validationSchemas: Map<string, StandardSchema | undefined> = new Map();\n private tables: Map<string, TableConfig> = new Map();\n private inTransaction: boolean = false;\n private syncQueue: Map<string, Promise<void>> = new Map();\n /** The order a table's schema declares its fields in, as the rows it computes list them */\n private keyOrders: Map<string, Set<string>> = new Map();\n /** The row each rowid was inserted from, per table loaded with detailed validation */\n private rowOriginsByRowid: Map<string, Map<string, RowOrigin>> = new Map();\n /**\n * The fields set and reset on each row (by rowid) since its table was last written back: a line\n * holds the fields a user wrote, so only what changed since it was written needs remembering\n */\n private fieldChanges: Map<string, Map<string, FieldChanges>> = new Map();\n private settleUndos: Array<() => void> | undefined;\n /**\n * The tables raw SQL may have changed since they were last written back: which fields it set is\n * unknown, so their rows are written back whole\n */\n private rawSqlTables: Set<string> = new Set();\n /** How many changes each table has seen, which tells a write-back whether one came after it read the rows */\n private changeGenerations: Map<string, number> = new Map();\n /**\n * The lines read, by rowid, that hold a field the table has no column for: kept to write that field\n * back, also once the row's primary key changed and its line can no longer be found by it\n */\n private linesWithUnknownFields: Map<string, Map<string, JsonObject>> = new Map();\n /** Whether a transaction's callback has returned and its files are being written back */\n private transactionClosing = false;\n /** Whether a transaction() call is past its guard but has not begun yet */\n private transactionStarting = false;\n /** Whether the running call came in through the object the running transaction() callback receives */\n private viaTransactionObject = false;\n /** Identifies the running transaction, so an object kept from an earlier one is not taken for its own */\n private transactionToken: object | undefined;\n /** The tables changed in the running transaction, or 'all' once raw SQL may have changed any */\n private transactionChanges: Set<string> | 'all' | undefined;\n /** Hash of each JSONL file's content as this database last read or wrote it */\n private fileHashes: Map<string, string> = new Map();\n /**\n * Hash of each JSONL file's content as this database last read or wrote it, kept for a table that\n * failed to load too: unlike fileHashes, it only tells whether a file changed and guards no write\n */\n private observedHashes: Map<string, string> = new Map();\n /** The JSONL files the data directories held when the tables were scanned */\n private scannedJsonlFiles: string[] = [];\n /** Tables left out because their files have no rows to infer the columns from */\n private emptyTables: Set<string> = new Set();\n /** Tables created from the columns `schemaOfEmptyTable` gave, which may lack a field the validator adds */\n private tablesFromGivenColumns: Set<string> = new Set();\n /** Each table's schema file and a hash of its content as the tables were loaded, or '' for none */\n private schemaFileStates: Map<string, string> = new Map();\n\n private constructor(config: DatabaseConfig<Tables>, dbPath?: string) {\n this.config = config;\n this.db = createDatabase(dbPath ?? ':memory:');\n }\n\n static create<Tables extends TableDefs>(config: DatabaseConfig<Tables>, dbPath?: string): LinesDB<Tables> {\n return new LinesDB<Tables>(config, dbPath);\n }\n\n /**\n * Initialize database by loading all JSONL files or a specific table\n * Uses dependency resolution to ensure foreign key references are loaded in correct order\n * @param options Optional configuration for initialization\n * @param options.tableName Optional table name to initialize. If not provided, initializes all tables\n * @param options.detailedValidate If true, performs detailed validation by inserting rows one by one to catch constraint violations\n * @param options.transform Optional transform function to apply to rows before validation (only applied to the specified tableName)\n * @returns Result wrapping a ValidationResult with validation status, errors, and warnings\n */\n async initialize(options?: {\n tableName?: string;\n detailedValidate?: boolean;\n transform?: (row: JsonObject) => JsonObject;\n }): Promise<Result<ValidationResult, Error>> {\n try {\n return ok(await this.initializeInternal(options));\n } catch (error) {\n return err(toError(error));\n }\n }\n\n private async initializeInternal(options?: {\n tableName?: string;\n detailedValidate?: boolean;\n transform?: (row: JsonObject) => JsonObject;\n }): Promise<ValidationResult> {\n if (this.hasSeveralDataDirs() && !this.config.schemaDir) {\n throw new Error(\n 'schemaDir is required when dataDir lists several directories: a data set directory does not hold the schemas of its tables',\n );\n }\n\n this.db.exec('PRAGMA query_only = OFF');\n try {\n return await this.loadTables(options);\n } finally {\n // Raw SQL through execute() or query() must not change a database whose changes cannot be written back\n if (this.isReadOnlyDataSet()) {\n this.db.exec('PRAGMA query_only = ON');\n }\n }\n }\n\n private async loadTables(options?: {\n tableName?: string;\n detailedValidate?: boolean;\n transform?: (row: JsonObject) => JsonObject;\n }): Promise<ValidationResult> {\n const allErrors: ValidationErrorDetail[] = [];\n const allWarnings: string[] = [];\n const allRowCounts = new Map<string, number>();\n const tableName = options?.tableName;\n const detailedValidate = options?.detailedValidate ?? false;\n const transform = options?.transform;\n\n // Scan directory for JSONL files\n this.emptyTables.clear();\n this.tables = await DirectoryScanner.scanDirectory(this.config.dataDir);\n this.scannedJsonlFiles = listJsonlFiles(this.tables);\n this.observedHashes.clear();\n this.schemaFileStates.clear();\n for (const [name, config] of this.tables) {\n this.schemaFileStates.set(name, await this.schemaFileState(name, config));\n }\n\n // Determine which tables to load\n const tablesToLoad = tableName ? [tableName] : Array.from(this.tables.keys());\n for (const name of tablesToLoad) this.tablesFromGivenColumns.delete(name);\n\n // Validate that all requested tables exist BEFORE starting to load\n for (const tableNameToLoad of tablesToLoad) {\n if (!this.tables.has(tableNameToLoad)) {\n const dataDirs = [this.config.dataDir].flat().map((dir) => `'${dir}'`);\n throw new Error(`Table '${tableNameToLoad}' not found in directory ${dataDirs.join(', ')}`);\n }\n }\n\n // Track loaded tables and tables currently being loaded (for circular dependency detection)\n const loadedTables = new Set<string>();\n const loadingTables = new Set<string>();\n const attemptedTables = new Set<string>(); // Track all attempted tables (loaded or not)\n const allDeferredForeignKeys: Array<{\n tableName: string;\n foreignKey: ForeignKeyDefinition;\n filePath: string;\n }> = [];\n\n // Load tables with dependency resolution\n for (const tableNameToLoad of tablesToLoad) {\n if (!attemptedTables.has(tableNameToLoad)) {\n // Only apply transform to the specified table\n const tableTransform = tableNameToLoad === tableName ? transform : undefined;\n const {\n errors,\n warnings,\n rowCounts: tableRowCounts,\n deferredForeignKeys,\n } = await this.loadTableWithDependencies(\n tableNameToLoad,\n loadedTables,\n loadingTables,\n attemptedTables,\n detailedValidate,\n tableTransform,\n );\n allErrors.push(...errors);\n allWarnings.push(...warnings);\n allDeferredForeignKeys.push(...deferredForeignKeys);\n for (const [k, v] of tableRowCounts) {\n allRowCounts.set(k, v);\n }\n }\n }\n\n // Validate deferred foreign keys (from circular dependencies) now that all tables are loaded\n if (detailedValidate && allDeferredForeignKeys.length > 0) {\n for (const { tableName: tName, foreignKey: fk, filePath } of allDeferredForeignKeys) {\n // Only validate if the referenced table was actually loaded\n if (!loadedTables.has(fk.references.table)) {\n continue;\n }\n const deferredErrors = this.validateDeferredForeignKey(tName, fk, filePath);\n allErrors.push(...deferredErrors);\n }\n }\n\n // Build per-table results\n const tableResults: TableValidationResult[] = tablesToLoad.map((name) => {\n const tableErrors = allErrors.filter((e) => e.tableName === name);\n const tableWarnings = allWarnings.filter((w) => w.includes(`'${name}'`));\n return {\n tableName: name,\n valid: tableErrors.length === 0,\n rowCount: allRowCounts.get(name) ?? 0,\n errors: tableErrors,\n warnings: tableWarnings,\n };\n });\n\n return {\n valid: allErrors.length === 0,\n errors: allErrors,\n warnings: allWarnings,\n tableResults,\n };\n }\n\n /**\n * Load a table and its dependencies recursively\n */\n private async loadTableWithDependencies(\n tableName: string,\n loadedTables: Set<string>,\n loadingTables: Set<string>,\n attemptedTables: Set<string>,\n detailedValidate: boolean,\n transform?: (row: JsonObject) => JsonObject,\n ): Promise<{\n errors: ValidationErrorDetail[];\n warnings: string[];\n rowCounts: Map<string, number>;\n deferredForeignKeys: Array<{\n tableName: string;\n foreignKey: ForeignKeyDefinition;\n filePath: string;\n }>;\n }> {\n const errors: ValidationErrorDetail[] = [];\n const warnings: string[] = [];\n const rowCounts = new Map<string, number>();\n const deferredForeignKeys: Array<{\n tableName: string;\n foreignKey: ForeignKeyDefinition;\n filePath: string;\n }> = [];\n\n // Skip if already attempted (loaded or not)\n if (attemptedTables.has(tableName)) {\n return { errors, warnings, rowCounts, deferredForeignKeys };\n }\n\n // Mark as attempted\n attemptedTables.add(tableName);\n\n // Check for circular dependencies\n if (loadingTables.has(tableName)) {\n throw new Error(`Circular dependency detected for table '${tableName}'`);\n }\n\n // Get table config\n const tableConfig = this.tables.get(tableName);\n if (!tableConfig) {\n throw new Error(`Table configuration not found for '${tableName}'`);\n }\n\n // Mark as currently loading\n loadingTables.add(tableName);\n\n try {\n // Load schema module to check for foreign key dependencies\n // We need to load the entire module to access foreignKeys export\n let foreignKeys: BiDirectionalSchema['foreignKeys'];\n\n try {\n const { pathToFileURL } = await import('node:url');\n const schemaPath = await this.findTableSchemaFile(tableName, tableConfig);\n if (schemaPath) {\n const schemaUrl = pathToFileURL(schemaPath).href;\n const schemaModule = await import(`${schemaUrl}?t=${Date.now()}`);\n\n // Try to get foreign keys from exported 'schema' or directly from module\n const schemaExport = schemaModule.schema || schemaModule.default;\n foreignKeys = schemaExport?.foreignKeys || schemaModule.foreignKeys;\n }\n } catch {\n // Schema file not found - will continue without validation\n }\n\n // If there are foreign key dependencies, load them first\n if (foreignKeys && foreignKeys.length > 0) {\n for (const fk of foreignKeys) {\n const referencedTable = fk.references.table;\n\n // Skip self-referencing foreign keys (e.g., nullable parent_id columns)\n if (referencedTable === tableName) {\n continue;\n }\n\n if (!attemptedTables.has(referencedTable)) {\n // Check if referenced table exists in our tables map\n if (this.tables.has(referencedTable)) {\n // Dependencies should not have transform applied\n const depResult = await this.loadTableWithDependencies(\n referencedTable,\n loadedTables,\n loadingTables,\n attemptedTables,\n detailedValidate,\n undefined,\n );\n errors.push(...depResult.errors);\n warnings.push(...depResult.warnings);\n deferredForeignKeys.push(...depResult.deferredForeignKeys);\n for (const [k, v] of depResult.rowCounts) {\n rowCounts.set(k, v);\n }\n } else {\n throw new Error(\n `Foreign key reference to non-existent table '${referencedTable}' in table '${tableName}'`,\n );\n }\n }\n }\n }\n\n // Determine which FK dependencies failed or are circular (attempted but not loaded)\n const failedDependencies = new Set<string>();\n const circularDependencies = new Set<string>();\n if (foreignKeys && foreignKeys.length > 0) {\n for (const fk of foreignKeys) {\n const referencedTable = fk.references.table;\n if (referencedTable === tableName) continue;\n if (attemptedTables.has(referencedTable) && !loadedTables.has(referencedTable)) {\n if (loadingTables.has(referencedTable)) {\n // Circular dependency: table is currently being loaded\n circularDependencies.add(referencedTable);\n } else {\n // Actual failure: table attempted but not loaded\n failedDependencies.add(referencedTable);\n }\n }\n }\n if (failedDependencies.size > 0) {\n for (const dep of failedDependencies) {\n const reason = this.emptyTables.has(dep) ? 'has no rows to read its columns from' : 'has validation errors';\n warnings.push(\n `Skipping foreign key validation for table '${tableName}': referenced table '${dep}' ${reason}`,\n );\n }\n }\n }\n\n // Combine failed and circular dependencies for table loading (both need FK skipping)\n const allSkippedDependencies = new Set([...failedDependencies, ...circularDependencies]);\n\n // Now load this table\n const {\n loaded,\n rowCount,\n errors: loadErrors,\n } = await this.loadTable(tableName, tableConfig, detailedValidate, transform, allSkippedDependencies);\n errors.push(...loadErrors);\n rowCounts.set(tableName, rowCount);\n\n if (loaded) {\n loadedTables.add(tableName);\n\n // Track circular dependency FKs for deferred validation\n if (foreignKeys && circularDependencies.size > 0) {\n for (const fk of foreignKeys) {\n if (circularDependencies.has(fk.references.table)) {\n deferredForeignKeys.push({\n tableName,\n foreignKey: fk,\n filePath: tableConfig.jsonlPath,\n });\n }\n }\n }\n } else {\n // Table was not loaded (e.g., empty data)\n if (rowCount === 0 && loadErrors.length === 0) this.emptyTables.add(tableName);\n warnings.push(`Table '${tableName}' was not loaded (no data or skipped)`);\n this.tables.delete(tableName);\n }\n } finally {\n // Remove from loading set\n loadingTables.delete(tableName);\n }\n\n return { errors, warnings, rowCounts, deferredForeignKeys };\n }\n\n /**\n * Find the schema file of a table in schemaDir, or next to the table's JSONL file when unset\n */\n private async findTableSchemaFile(tableName: string, config: TableConfig): Promise<string | undefined> {\n return findSchemaFile(this.config.schemaDir ?? dirname(config.jsonlPath), tableName);\n }\n\n /**\n * Load a single table from JSONL file\n * @returns Object with loaded status and validation errors\n */\n private async loadTable(\n tableName: string,\n config: TableConfig,\n detailedValidate: boolean,\n transform?: (row: JsonObject) => JsonObject,\n failedDependencies?: Set<string>,\n ): Promise<{ loaded: boolean; rowCount: number; errors: ValidationErrorDetail[] }> {\n // Read every JSONL file of the table, remembering where each row came from\n let data: JsonObject[] = [];\n const origins: RowOrigin[] = [];\n const contentHashes = new Map<string, string>();\n for (const jsonlPath of config.jsonlPaths ?? [config.jsonlPath]) {\n const readResult = await JsonlReader.readSnapshot(jsonlPath);\n if (!readResult.ok) {\n throw readResult.error;\n }\n const { rows, contentHash } = readResult.value;\n if (!rows.ok) {\n throw rows.error;\n }\n if (contentHash !== undefined) {\n contentHashes.set(jsonlPath, contentHash);\n this.observedHashes.set(jsonlPath, contentHash);\n }\n rows.value.forEach((row, rowIndex) => {\n data.push(row);\n origins.push({ file: jsonlPath, rowIndex });\n });\n }\n\n // Apply transform if provided (before validation)\n const transformedFields: string[][] = [];\n if (transform) {\n data = data.map((row) => {\n const transformed = transform(row);\n transformedFields.push(\n Object.keys(transformed).filter((key) => JSON.stringify(transformed[key]) !== JSON.stringify(row[key])),\n );\n return transformed;\n });\n }\n\n // Load validation schema if provided or try to auto-load\n let validationSchema = config.validationSchema;\n const schemaMetadata: {\n primaryKey?: string;\n foreignKeys?: BiDirectionalSchema['foreignKeys'];\n indexes?: BiDirectionalSchema['indexes'];\n } = {};\n\n const schemaPath = config.validationSchema ? undefined : await this.findTableSchemaFile(tableName, config);\n if (!validationSchema && schemaPath) {\n // Not loaded without validation when its schema file fails to load: rows written then would skip\n // the checks the file means to make; the error names the file and why it failed\n validationSchema = await SchemaLoader.loadSchema(config.jsonlPath, dirname(schemaPath));\n }\n\n // Load schema metadata (foreignKeys, primaryKey, indexes) from schema module\n // SchemaLoader.loadSchema() only returns the validation schema object, not metadata\n if (!config.validationSchema) {\n // Only load if not already provided via config\n try {\n const { pathToFileURL } = await import('node:url');\n if (!schemaPath) throw new Error('Schema file not found');\n const schemaUrl = pathToFileURL(schemaPath).href;\n const schemaModule = await import(`${schemaUrl}?t=${Date.now()}`);\n\n // Try to get metadata from exported 'schema' or directly from module\n const schemaExport = schemaModule.schema || schemaModule.default;\n\n if (schemaExport?.primaryKey) {\n schemaMetadata.primaryKey = schemaExport.primaryKey;\n } else if (schemaModule.primaryKey) {\n schemaMetadata.primaryKey = schemaModule.primaryKey;\n }\n\n if (schemaExport?.foreignKeys) {\n schemaMetadata.foreignKeys = schemaExport.foreignKeys;\n } else if (schemaModule.foreignKeys) {\n schemaMetadata.foreignKeys = schemaModule.foreignKeys;\n }\n\n if (schemaExport?.indexes) {\n schemaMetadata.indexes = schemaExport.indexes;\n } else if (schemaModule.indexes) {\n schemaMetadata.indexes = schemaModule.indexes;\n }\n\n // Debug: log loaded metadata\n if (process.env.DEBUG_LINES_DB) {\n console.log(`[lines-db] Schema metadata for ${tableName}:`);\n console.log(` primaryKey: ${schemaMetadata.primaryKey}`);\n console.log(` foreignKeys: ${JSON.stringify(schemaMetadata.foreignKeys)}`);\n console.log(` indexes: ${JSON.stringify(schemaMetadata.indexes)}`);\n }\n } catch (_error) {\n // Schema file not found - this is OK\n // Debug: log error for investigation\n if (process.env.DEBUG_LINES_DB) {\n console.warn(\n `[lines-db] Failed to load schema metadata for ${tableName}:`,\n _error instanceof Error ? _error.message : String(_error),\n );\n }\n }\n }\n\n this.validationSchemas.set(tableName, validationSchema);\n\n // Validate data first and collect validated (transformed) data\n const validationErrors: Array<{\n rowIndex: number;\n rowData: JsonObject;\n error: ValidationError;\n }> = [];\n const validatedData: JsonObject[] = [];\n // The field order describes the rows this load computes, so a reload does not keep the order a\n // schema had the last time the table was loaded\n this.keyOrders.delete(tableName);\n\n for (let rowIndex = 0; rowIndex < data.length; rowIndex++) {\n const row = data[rowIndex];\n try {\n const validatedRow = this.validateAndTransform(tableName, row);\n this.recordKeyOrder(tableName, validatedRow);\n validatedData.push(validatedRow);\n } catch (error) {\n if (error instanceof Error && error.name === 'ValidationError') {\n validationErrors.push({\n rowIndex,\n rowData: row,\n error: error as ValidationError,\n });\n } else {\n throw error;\n }\n }\n }\n\n // Convert validation errors to ValidationErrorDetail format\n const validationErrorDetails: ValidationErrorDetail[] = validationErrors.map((ve) => ({\n ...origins[ve.rowIndex],\n tableName,\n issues: ve.error.issues,\n type: 'schema' as const,\n }));\n\n if (validationErrors.length > 0) {\n // Return errors instead of throwing\n return { loaded: false, rowCount: data.length, errors: validationErrorDetails };\n }\n\n // Determine schema - infer from validated data if auto-inference is enabled\n let schema: TableSchema;\n let inferredSchema: TableSchema | undefined;\n\n // Always infer schema from validated data to capture valueType information (e.g., boolean)\n if (validatedData.length > 0) {\n inferredSchema = unwrap(JsonlReader.inferSchema(tableName, validatedData));\n }\n\n if (config.schema) {\n schema = config.schema;\n // Merge valueType information from inferred schema\n if (inferredSchema) {\n for (const inferredCol of inferredSchema.columns) {\n const schemaCol = schema.columns.find((c) => c.name === inferredCol.name);\n if (schemaCol && inferredCol.valueType && !schemaCol.valueType) {\n schemaCol.valueType = inferredCol.valueType;\n }\n }\n }\n } else if (config.autoInferSchema !== false) {\n if (validatedData.length === 0) {\n const declared = await this.config.schemaOfEmptyTable?.({ tableName, schemaPath });\n if (!declared || declared.columns.length === 0) return { loaded: false, rowCount: 0, errors: [] };\n schema = { ...declared, name: tableName, columns: declared.columns.map((column) => ({ ...column })) };\n this.tablesFromGivenColumns.add(tableName);\n } else {\n schema = inferredSchema!;\n }\n } else {\n // Critical error - throw exception\n throw new Error(`No schema provided for table ${tableName} and autoInferSchema is disabled`);\n }\n\n // Enhance schema with constraints from validation schema and schema metadata\n // Priority: config.validationSchema (as BiDirectionalSchema) > schemaMetadata\n const biSchema = validationSchema as BiDirectionalSchema;\n const primaryKey = biSchema?.primaryKey || schemaMetadata.primaryKey;\n const foreignKeys = biSchema?.foreignKeys || schemaMetadata.foreignKeys;\n const indexes = biSchema?.indexes || schemaMetadata.indexes;\n\n if (primaryKey && !schema.columns.some((col) => col.primaryKey)) {\n // Add primary key constraint to column\n const col = schema.columns.find((c) => c.name === primaryKey);\n if (col) {\n col.primaryKey = true;\n }\n } else if (!primaryKey && !schema.columns.some((col) => col.primaryKey)) {\n // If no primary key is defined, use 'id' column as primary key if it exists\n // This matches the behavior of JsonlReader.inferSchema()\n const idColumn = schema.columns.find((c) => c.name === 'id');\n if (idColumn) {\n idColumn.primaryKey = true;\n }\n }\n if (foreignKeys) {\n schema.declaredForeignKeys = foreignKeys;\n schema.foreignKeys =\n failedDependencies && failedDependencies.size > 0\n ? foreignKeys.filter((fk) => !failedDependencies.has(fk.references.table))\n : foreignKeys;\n }\n if (indexes) {\n schema.indexes = indexes;\n\n // Apply unique constraint from single-column unique indexes to column definitions\n // This is required for foreign key references, as SQLite requires the referenced column\n // to have a UNIQUE constraint in the table definition (not just an index)\n for (const index of indexes) {\n if (index.unique && index.columns.length === 1) {\n const col = schema.columns.find((c) => c.name === index.columns[0]);\n if (col && !col.unique && !col.primaryKey) {\n col.unique = true;\n }\n }\n }\n }\n\n if (schema === inferredSchema) {\n this.relaxColumnsTheSchemaLeavesOptional(tableName, schema, data[0]);\n }\n\n this.schemas.set(tableName, schema);\n\n // Create table\n this.createTable(schema);\n\n // Insert validated data (with detailed validation if requested)\n if (detailedValidate || this.config.writeDataSets) {\n const insertErrors = this.insertDataWithDetailedValidation(tableName, schema, validatedData, origins);\n if (insertErrors.length > 0) {\n return { loaded: false, rowCount: data.length, errors: insertErrors };\n }\n } else {\n this.insertData(tableName, schema, validatedData);\n }\n\n this.fieldChanges.delete(tableName);\n this.linesWithUnknownFields.delete(tableName);\n const columnNames = new Set(schema.columns.map((column) => column.name));\n const withUnknown = data.map((row) => Object.keys(row).some((key) => !columnNames.has(key)));\n if (transformedFields.some((fields) => fields.length > 0) || withUnknown.includes(true)) {\n const rowids = this.queryInternal<JsonObject>(\n `SELECT rowid AS \"${ROWID_ALIAS}\" FROM ${this.quoteTableName(tableName)} ORDER BY rowid`,\n );\n const lines = new Map<string, JsonObject>();\n const sourceIndexes = new Map(origins.map((origin, index) => [origin, index]));\n rowids.forEach((row, index) => {\n const rowid = row[ROWID_ALIAS] as number | bigint;\n const origin = this.rowOriginsByRowid.get(tableName)?.get(String(rowid));\n const sourceIndex = origin ? (sourceIndexes.get(origin) ?? index) : index;\n const set = transformedFields[sourceIndex] ?? [];\n if (set.length > 0) this.noteFieldChanges(tableName, rowid, { set });\n if (withUnknown[sourceIndex]) lines.set(String(rowid), data[sourceIndex]);\n });\n this.linesWithUnknownFields.set(tableName, lines);\n }\n\n for (const [jsonlPath, contentHash] of contentHashes) {\n this.fileHashes.set(jsonlPath, contentHash);\n }\n return { loaded: true, rowCount: data.length, errors: [] };\n }\n\n /**\n * A column no row holds a value in has no type to read a boolean or an object back with, and so reads\n * back as 1 or as JSON text. The first value written settles it, and a string settles it as text so an\n * object written later does not turn that text into JSON. Not asked of the schema: it names no type at\n * run time. Returns what puts the columns back, which a write that did not go in, or a transaction that\n * rolled back, must call: the value that settled it is not in the table\n */\n private settleColumnsNoRowHolds(schema: TableSchema | undefined, written: JsonObject): () => void {\n const before: Array<[ColumnDefinition, ColumnDefinition['type'], ColumnDefinition['valueType']]> = [];\n for (const column of schema?.columns ?? []) {\n const value = written[column.name];\n if (column.type !== 'NULL' || value === null || value === undefined) continue;\n before.push([column, column.type, column.valueType]);\n if (typeof value === 'boolean') {\n column.type = 'INTEGER';\n column.valueType = 'boolean';\n } else if (typeof value === 'string') {\n column.type = 'TEXT';\n } else if (typeof value === 'number') {\n column.type = Number.isInteger(value) ? 'INTEGER' : 'REAL';\n } else if (typeof value === 'object' && !(value instanceof Uint8Array)) {\n column.type = 'JSON';\n } else {\n before.pop();\n }\n }\n const undo = () => {\n for (const [column, type, valueType] of before) {\n column.type = type;\n column.valueType = valueType;\n }\n };\n this.settleUndos?.push(undo);\n return undo;\n }\n\n /**\n * A column every row holds is inferred NOT NULL, which refuses a later row that leaves it out even\n * where the schema takes that row. The sample row without the field says whether the schema does.\n * A column the schema fills in stays NOT NULL: the row is stored as the schema leaves it\n */\n private relaxColumnsTheSchemaLeavesOptional(tableName: string, schema: TableSchema, sample: JsonObject | undefined) {\n if (!sample || !this.validationSchemas.get(tableName)) return;\n for (const column of schema.columns) {\n if (!column.notNull || column.primaryKey || !(column.name in sample)) continue;\n const { [column.name]: _left, ...without } = sample;\n try {\n if ((this.validateAndTransform(tableName, without)[column.name] ?? null) === null) {\n column.notNull = false;\n }\n } catch {\n // Not rethrown: a validator written for whole rows may throw on one without the field, which is no reason to fail the load\n }\n }\n }\n\n /**\n * Create table in SQLite with constraints and indexes\n */\n private createTable(schema: TableSchema): void {\n // Note: Foreign key constraints are enabled at database connection level (see sqlite-adapter.ts)\n // No need to enable them here for each table\n\n // Quote table name to handle special characters\n const quotedTableName = this.quoteTableName(schema.name);\n\n // Build a set of columns that should have UNIQUE constraint\n // This includes columns marked as unique in schema AND single-column unique indexes\n // The latter is required for foreign key references, as SQLite requires the referenced column\n // to have a UNIQUE constraint in the table definition (not just a separately created index)\n const uniqueColumns = new Set<string>();\n for (const col of schema.columns) {\n if (col.unique) {\n uniqueColumns.add(col.name);\n }\n }\n if (schema.indexes) {\n for (const index of schema.indexes) {\n if (index.unique && index.columns.length === 1) {\n uniqueColumns.add(index.columns[0]);\n }\n }\n }\n\n const columnDefs = schema.columns.map((col) => {\n // JSON type is stored as TEXT in SQLite\n const sqlType = col.type === 'JSON' ? 'TEXT' : col.type;\n const parts = [this.quoteIdentifier(col.name), sqlType];\n if (col.primaryKey) parts.push('PRIMARY KEY');\n if (col.notNull) parts.push('NOT NULL');\n if (uniqueColumns.has(col.name) && !col.primaryKey) parts.push('UNIQUE');\n return parts.join(' ');\n });\n\n // Add foreign key constraints\n const foreignKeyDefs: string[] = [];\n if (schema.foreignKeys && schema.foreignKeys.length > 0) {\n for (const fk of schema.foreignKeys) {\n const fkParts = [\n `FOREIGN KEY (${this.quoteIdentifier(fk.column)})`,\n `REFERENCES ${this.quoteTableName(fk.references.table)}(${this.quoteIdentifier(fk.references.column)})`,\n ];\n if (fk.onDelete) {\n fkParts.push(`ON DELETE ${fk.onDelete}`);\n }\n if (fk.onUpdate) {\n fkParts.push(`ON UPDATE ${fk.onUpdate}`);\n }\n foreignKeyDefs.push(fkParts.join(' '));\n }\n }\n\n const allDefs = [...columnDefs, ...foreignKeyDefs];\n const sql = `CREATE TABLE IF NOT EXISTS ${quotedTableName} (${allDefs.join(', ')})`;\n this.db.exec(sql);\n if (this.hasSeveralDataDirs() && this.config.writeDataSets) {\n const moves = this.quoteIdentifier(this.rowMovesTable);\n const trigger = this.quoteIdentifier(`${this.rowMovesTable}_${schema.name}`);\n const name = `'${schema.name.replace(/'/g, \"''\")}'`;\n this.db.exec(`CREATE TEMP TABLE IF NOT EXISTS ${moves} (tableName TEXT, oldRowid INTEGER, newRowid INTEGER)`);\n this.db.exec(`CREATE TEMP TRIGGER IF NOT EXISTS ${trigger} AFTER UPDATE ON ${quotedTableName}\n WHEN OLD.rowid != NEW.rowid BEGIN\n INSERT INTO ${moves} VALUES (${name}, OLD.rowid, NEW.rowid);\n END`);\n }\n\n // Create indexes\n if (schema.indexes && schema.indexes.length > 0) {\n for (let i = 0; i < schema.indexes.length; i++) {\n const index = schema.indexes[i];\n // Create safe index name by replacing special characters\n const safeTableName = schema.name.replace(/[^a-zA-Z0-9]/g, '_');\n const resolvedIndexName = index.name || `idx_${safeTableName}_${index.columns.join('_')}_${i}`;\n const uniqueKeyword = index.unique ? 'UNIQUE ' : '';\n const indexSql = `CREATE ${uniqueKeyword}INDEX IF NOT EXISTS ${this.quoteIdentifier(resolvedIndexName)} ON ${quotedTableName} (${index.columns\n .map((col) => this.quoteIdentifier(col))\n .join(', ')})`;\n this.db.exec(indexSql);\n }\n }\n }\n\n /**\n * Quote table name to handle special characters in SQL\n */\n private quoteTableName(tableName: string): string {\n return this.quoteIdentifier(tableName);\n }\n\n /**\n * Quote identifier for SQL statements, escaping embedded quotes\n */\n private quoteIdentifier(identifier: string): string {\n return `\"${identifier.replace(/\"/g, '\"\"')}\"`;\n }\n\n /**\n * Insert data into table using batch insert (multiple rows per SQL)\n * SQLite has a parameter limit (default 999), so we batch rows accordingly\n * Throws exception if any constraint violation occurs\n */\n private insertData(tableName: string, schema: TableSchema, data: JsonObject[]): void {\n if (data.length === 0) return;\n\n const columnNames = schema.columns.map((col) => col.name);\n const quotedColumns = columnNames.map((name) => this.quoteIdentifier(name));\n const columnsByName = new Map(schema.columns.map((column) => [column.name, column]));\n const columnCount = columnNames.length;\n\n // Calculate batch size to stay under SQLite's parameter limit (999)\n // Leave some margin for safety\n const maxBatchSize = Math.floor(900 / columnCount);\n const batchSize = Math.max(1, Math.min(maxBatchSize, 100));\n\n // Process data in batches\n for (let i = 0; i < data.length; i += batchSize) {\n const batch = data.slice(i, i + batchSize);\n const rowPlaceholders = columnNames.map(() => '?').join(', ');\n const valuesPlaceholders = batch.map(() => `(${rowPlaceholders})`).join(', ');\n const sql = `INSERT INTO ${this.quoteTableName(tableName)} (${quotedColumns.join(', ')}) VALUES ${valuesPlaceholders}`;\n\n const values: (string | number | bigint | null | Uint8Array)[] = [];\n for (const row of batch) {\n for (const col of columnNames) {\n values.push(this.normalizeValue(row[col], columnsByName.get(col)));\n }\n }\n\n const stmt = this.db.prepare(sql);\n stmt.run(...values);\n }\n }\n\n /**\n * Insert data into table one row at a time with detailed error reporting\n * This is used for validation to catch constraint violations\n */\n private insertDataWithDetailedValidation(\n tableName: string,\n schema: TableSchema,\n data: JsonObject[],\n origins: RowOrigin[],\n ): ValidationErrorDetail[] {\n const errors: ValidationErrorDetail[] = [];\n const columnNames = schema.columns.map((col) => col.name);\n const quotedColumns = columnNames.map((name) => this.quoteIdentifier(name));\n const placeholders = columnNames.map(() => '?').join(', ');\n const sql = `INSERT INTO ${this.quoteTableName(tableName)} (${quotedColumns.join(', ')}) VALUES (${placeholders})`;\n const columnsByName = new Map(schema.columns.map((column) => [column.name, column]));\n\n const stmt = this.db.prepare(sql);\n const rowOrigins = new Map<string, RowOrigin>();\n this.rowOriginsByRowid.set(tableName, rowOrigins);\n\n for (let rowIndex = 0; rowIndex < data.length; rowIndex++) {\n const row = data[rowIndex];\n try {\n const values = columnNames.map((col) => this.normalizeValue(row[col], columnsByName.get(col)));\n const { lastInsertRowid } = stmt.run(...values);\n rowOrigins.set(String(lastInsertRowid), origins[rowIndex]);\n } catch (error) {\n // Constraint violation occurred - analyze and record details\n const constraintError = this.analyzeConstraintError(\n error,\n origins[rowIndex].file,\n tableName,\n origins[rowIndex].rowIndex,\n row,\n schema.foreignKeys || [],\n );\n if (constraintError) {\n errors.push(constraintError);\n }\n }\n }\n\n return errors;\n }\n\n /**\n * Analyze constraint error and extract detailed information\n */\n private analyzeConstraintError(\n error: unknown,\n file: string,\n tableName: string,\n rowIndex: number,\n row: JsonObject,\n foreignKeys: ForeignKeyDefinition[],\n ): ValidationErrorDetail | null {\n const errorMessage = error instanceof Error ? error.message : String(error);\n\n // Foreign key constraint\n if (errorMessage.includes('FOREIGN KEY constraint failed')) {\n // Find which foreign key failed\n for (const fk of foreignKeys) {\n const fkValue = row[fk.column];\n if (fkValue === null || fkValue === undefined) continue;\n\n // Check if referenced value exists\n try {\n const result = this.queryInternal(\n `SELECT COUNT(*) as count FROM ${this.quoteIdentifier(fk.references.table)} WHERE ${this.quoteIdentifier(fk.references.column)} = ?`,\n [this.normalizeValue(fkValue, this.columnOf(fk.references.table, fk.references.column))],\n );\n if (result.length > 0 && (result[0] as { count: number }).count === 0) {\n return {\n file,\n tableName,\n rowIndex,\n issues: [],\n type: 'foreignKey',\n foreignKeyError: {\n column: fk.column,\n value: fkValue,\n referencedTable: fk.references.table,\n referencedColumn: fk.references.column,\n },\n };\n }\n } catch (_) {\n // Referenced table doesn't exist yet\n }\n }\n }\n\n // Other constraint errors (primary key, unique, etc.)\n return {\n file,\n tableName,\n rowIndex,\n issues: [\n {\n message: errorMessage,\n path: [],\n },\n ],\n type: 'schema',\n };\n }\n\n /**\n * Validate a deferred foreign key constraint after all tables have been loaded.\n * Used for circular dependency FK validation.\n */\n private validateDeferredForeignKey(\n tableName: string,\n fk: ForeignKeyDefinition,\n filePath: string,\n ): ValidationErrorDetail[] {\n const errors: ValidationErrorDetail[] = [];\n const quotedTable = this.quoteTableName(tableName);\n const quotedColumn = this.quoteIdentifier(fk.column);\n const quotedRefTable = this.quoteTableName(fk.references.table);\n const quotedRefColumn = this.quoteIdentifier(fk.references.column);\n\n // Find rows where the FK value does not exist in the referenced table\n const sql = `SELECT rowid as rid, ${quotedColumn} as val FROM ${quotedTable} WHERE ${quotedColumn} IS NOT NULL AND ${quotedColumn} NOT IN (SELECT ${quotedRefColumn} FROM ${quotedRefTable})`;\n\n try {\n const rows = this.queryInternal<{ rid: number | bigint; val: string | number }>(sql);\n const rowOrigins = this.rowOriginsByRowid.get(tableName);\n for (const row of rows) {\n errors.push({\n ...(rowOrigins?.get(String(row.rid)) ?? { file: filePath, rowIndex: Number(row.rid) - 1 }),\n tableName,\n issues: [],\n type: 'foreignKey',\n foreignKeyError: {\n column: fk.column,\n value: row.val,\n referencedTable: fk.references.table,\n referencedColumn: fk.references.column,\n },\n });\n }\n } catch (_) {\n // Table might not exist - skip validation\n }\n\n return errors;\n }\n\n /**\n * Execute a raw SQL query\n */\n query<T = unknown>(sql: string, params: (string | number | bigint | null | Uint8Array)[] = []): Result<T[], Error> {\n try {\n this.enforceReadOnlySql();\n this.refuseUnsafeSql(sql);\n return ok(this.trackRawSql(() => this.readOnlyWhileTransactionSettles(() => this.queryInternal<T>(sql, params))));\n } catch (error) {\n return err(toError(error));\n }\n }\n\n private queryInternal<T = unknown>(sql: string, params: (string | number | bigint | null | Uint8Array)[] = []): T[] {\n const stmt = this.db.prepare(sql);\n return stmt.all(...params) as T[];\n }\n\n /**\n * Execute a SQL query that returns a single row\n */\n queryOne<T = unknown>(\n sql: string,\n params: (string | number | bigint | null | Uint8Array)[] = [],\n ): Result<T | null, Error> {\n try {\n this.enforceReadOnlySql();\n this.refuseUnsafeSql(sql);\n return ok(\n this.trackRawSql(() => this.readOnlyWhileTransactionSettles(() => this.queryOneInternal<T>(sql, params))),\n );\n } catch (error) {\n return err(toError(error));\n }\n }\n\n private queryOneInternal<T = unknown>(\n sql: string,\n params: (string | number | bigint | null | Uint8Array)[] = [],\n ): T | null {\n const stmt = this.db.prepare(sql);\n const result = stmt.get(...params);\n return result === undefined ? null : (result as T);\n }\n\n /**\n * Execute a SQL statement (INSERT, UPDATE, DELETE)\n */\n execute(\n sql: string,\n params: (string | number | bigint | null | Uint8Array)[] = [],\n ): Result<{ changes: number | bigint; lastInsertRowid: number | bigint }, Error> {\n try {\n this.enforceReadOnlySql();\n this.refuseUnsafeSql(sql);\n this.refuseWhileTransactionSettles('run SQL');\n return ok(this.trackRawSql(() => this.readOnlyWhileTransactionSettles(() => this.executeInternal(sql, params))));\n } catch (error) {\n return err(toError(error));\n }\n }\n\n /**\n * Run a caller's SQL, and when it changed rows, write back every table whole: which tables and\n * fields raw SQL changed is unknown, and a query() can change rows with RETURNING too\n */\n private trackRawSql<T>(run: () => T): T {\n const before = this.totalChanges();\n // Not only when it returns: SQL of several statements can change rows and then fail on a later one\n try {\n return run();\n } finally {\n if (this.totalChanges() !== before) {\n for (const tableName of this.schemas.keys()) {\n this.rawSqlTables.add(tableName);\n this.noteChange(tableName);\n }\n this.forgetLinesOfGoneRows(this.schemas.keys());\n if (this.transactionChanges) this.transactionChanges = 'all';\n }\n }\n }\n\n private totalChanges(): number {\n return Number((this.db.prepare('SELECT total_changes() AS n').get() as { n: number | bigint }).n);\n }\n\n private executeInternal(\n sql: string,\n params: (string | number | bigint | null | Uint8Array)[] = [],\n ): { changes: number | bigint; lastInsertRowid: number | bigint } {\n const stmt = this.db.prepare(sql);\n const result = stmt.run(...params);\n if (this.hasSeveralDataDirs() && this.config.writeDataSets) {\n const moves = this.quoteIdentifier(this.rowMovesTable);\n const changes = this.queryInternal<{ tableName: string; oldRowid: number | bigint; newRowid: number | bigint }>(\n `SELECT tableName, oldRowid, newRowid FROM ${moves} ORDER BY rowid`,\n );\n for (const change of changes)\n this.moveRowMetadata(change.tableName, String(change.oldRowid), String(change.newRowid));\n if (changes.length > 0) this.db.exec(`DELETE FROM ${moves}`);\n }\n return result;\n }\n\n /**\n * Find rows by condition (supports OR/AND with arrays and function filters)\n * If where is not provided, returns all rows\n */\n find<K extends keyof Tables & string>(tableName: K, where?: WhereCondition<Tables[K]>): Result<Tables[K][], Error> {\n try {\n return ok(this.findInternal(tableName, where));\n } catch (error) {\n return err(toError(error));\n }\n }\n\n private findInternal<K extends keyof Tables & string>(tableName: K, where?: WhereCondition<Tables[K]>): Tables[K][] {\n // If no where condition, return all rows\n if (where === undefined) {\n const rows = this.queryInternal(`SELECT * FROM ${this.quoteTableName(tableName)}`);\n return rows.map((row) => this.deserializeRow(tableName, row)) as Tables[K][];\n }\n\n // Handle empty array - should return no results\n if (Array.isArray(where) && where.length === 0) {\n return [];\n }\n\n const { sql, values, functionFilters, hasOrWithFunctionFilters } = this.buildWhereClause(where, tableName);\n\n let rows: Tables[K][];\n\n // If OR condition has function filters, get all rows and evaluate in JS\n if (hasOrWithFunctionFilters) {\n const rawRows = this.queryInternal(`SELECT * FROM ${this.quoteTableName(tableName)}`);\n rows = rawRows.map((row) => this.deserializeRow(tableName, row)) as Tables[K][];\n return this.applyOrConditionWithFilters(rows, where as WhereCondition<Tables[K]>);\n }\n\n // Normal case: use SQL WHERE clause\n if (sql) {\n const rawRows = this.queryInternal(`SELECT * FROM ${this.quoteTableName(tableName)} WHERE ${sql}`, values);\n rows = rawRows.map((row) => this.deserializeRow(tableName, row)) as Tables[K][];\n } else {\n // If only function filters (AND case), get all rows\n const rawRows = this.queryInternal(`SELECT * FROM ${this.quoteTableName(tableName)}`);\n rows = rawRows.map((row) => this.deserializeRow(tableName, row)) as Tables[K][];\n }\n\n // Apply function filters for AND conditions\n return this.applyFunctionFilters(rows, functionFilters);\n }\n\n /**\n * Find a single row by condition (supports OR/AND with arrays and function filters)\n */\n findOne<K extends keyof Tables & string>(\n tableName: K,\n where: WhereCondition<Tables[K]>,\n ): Result<Tables[K] | null, Error> {\n try {\n return ok(this.findOneInternal(tableName, where));\n } catch (error) {\n return err(toError(error));\n }\n }\n\n private findOneInternal<K extends keyof Tables & string>(\n tableName: K,\n where: WhereCondition<Tables[K]>,\n ): Tables[K] | null {\n const { sql, values, functionFilters } = this.buildWhereClause(where, tableName);\n\n let rows: Tables[K][];\n if (sql) {\n const rawRows = this.queryInternal(`SELECT * FROM ${this.quoteTableName(tableName)} WHERE ${sql}`, values);\n rows = rawRows.map((row) => this.deserializeRow(tableName, row)) as Tables[K][];\n } else {\n // If only function filters, get all rows\n const rawRows = this.queryInternal(`SELECT * FROM ${this.quoteTableName(tableName)}`);\n rows = rawRows.map((row) => this.deserializeRow(tableName, row)) as Tables[K][];\n }\n\n // Apply function filters and return first match\n const filtered = this.applyFunctionFilters(rows, functionFilters);\n return filtered.length > 0 ? filtered[0] : null;\n }\n\n /**\n * Deserialize JSON columns in a row\n */\n private deserializeRow<T>(tableName: string, row: T): T {\n const schema = this.schemas.get(tableName);\n if (!schema) return row;\n\n const deserializedRow = { ...row } as Record<string, unknown>;\n\n for (const column of schema.columns) {\n const colName = column.name;\n if (!(colName in deserializedRow)) continue;\n\n const value = deserializedRow[colName];\n\n if (column.type === 'JSON' && typeof value === 'string') {\n try {\n deserializedRow[colName] = JSON.parse(value);\n } catch (error) {\n // If parsing fails, keep the original value\n console.warn(`Failed to parse JSON column ${colName}:`, error);\n }\n continue;\n }\n\n if (column.valueType === 'boolean') {\n if (typeof value === 'number') {\n deserializedRow[colName] = value === 0 ? false : true;\n } else if (typeof value === 'bigint') {\n deserializedRow[colName] = value === 0n ? false : true;\n }\n }\n }\n\n return deserializedRow as T;\n }\n\n /**\n * Validate data using StandardSchema and return the transformed value\n * Note: Only synchronous validation is supported\n */\n private validateAndTransform(tableName: string, data: unknown): JsonObject {\n const schema = this.validationSchemas.get(tableName);\n if (!schema) {\n return data as JsonObject;\n }\n\n const result = schema['~standard'].validate(data);\n\n // Only synchronous validation is supported\n if (result instanceof Promise) {\n throw new Error('Asynchronous validation is not supported. Please use synchronous validation schemas.');\n }\n\n if (result.issues && result.issues.length > 0) {\n // Format detailed error message with all validation issues\n const issueMessages = result.issues\n .map((issue) => {\n // Handle path: can be array of PathSegment or undefined\n let pathStr = 'root';\n if (issue.path && issue.path.length > 0) {\n pathStr = issue.path\n .map((segment) => {\n // PathSegment can be { key: PropertyKey } or just PropertyKey\n if (typeof segment === 'object' && segment !== null && 'key' in segment) {\n return String(segment.key);\n }\n return String(segment);\n })\n .join('.');\n }\n return ` - ${pathStr}: ${issue.message}`;\n })\n .join('\\n');\n\n const errorMessage = `Validation failed for table '${tableName}':\\n${issueMessages}`;\n const error = new Error(errorMessage) as ValidationError;\n error.name = 'ValidationError';\n error.issues = result.issues;\n throw error;\n }\n\n // Return the transformed value from validation\n // When there are no issues, result.value should be present\n const transformedValue = ('value' in result ? result.value : data) as JsonObject;\n\n // Convert undefined values to null for JSON compatibility\n const normalizedValue: JsonObject = {};\n for (const [key, value] of Object.entries(transformedValue)) {\n normalizedValue[key] = value === undefined ? null : value;\n }\n\n return normalizedValue;\n }\n\n /**\n * Validate data using StandardSchema (without returning transformed value)\n * Note: Only synchronous validation is supported\n */\n private validateData(tableName: string, data: unknown): void {\n // Use validateAndTransform but discard the result\n this.validateAndTransform(tableName, data);\n }\n\n /**\n * Remember the order a computed row lists its fields in - the order the schema declares them, since\n * that is the order a hook or a validation fills a row in. A sync inserts a key the line did not\n * have at the place this order gives it.\n */\n private recordKeyOrder(tableName: string, row: JsonObject): void {\n const order = this.keyOrders.get(tableName) ?? new Set<string>();\n for (const key of Object.keys(row)) {\n // A set keeps the order keys were added in, so a field only some rows carry lands after the\n // ones already seen - which is where the row that carries it puts it too\n order.add(key);\n }\n this.keyOrders.set(tableName, order);\n }\n\n /**\n * Insert a row into a table with validation\n */\n insert<K extends keyof Tables & string>(\n tableName: K,\n data: Tables[K],\n options?: { dataDir?: string },\n ): Result<{ changes: number | bigint; lastInsertRowid: number | bigint }, Error> {\n try {\n return ok(this.insertInternal(tableName, data, options));\n } catch (error) {\n return err(toError(error));\n }\n }\n\n private insertInternal<K extends keyof Tables & string>(\n tableName: K,\n data: Tables[K],\n options?: { dataDir?: string },\n ): { changes: number | bigint; lastInsertRowid: number | bigint } {\n this.assertMutable(tableName);\n let destination: string | undefined;\n if (this.hasSeveralDataDirs()) {\n const dataDir = options?.dataDir;\n if (!dataDir || ![this.config.dataDir].flat().some((dir) => resolve(dir) === resolve(dataDir))) {\n throw new Error('Choose an insert dataDir from the configured data directories');\n }\n destination = join(\n [this.config.dataDir].flat().find((dir) => resolve(dir) === resolve(dataDir))!,\n `${tableName}.jsonl`,\n );\n }\n\n // Not inserting the row as given: a value the schema fills in would be missing, unlike in a loaded row\n const row = this.validateAndTransform(tableName, data);\n\n const schema = this.schemas.get(tableName);\n if (!schema) {\n throw new Error(`Table ${tableName} does not exist`);\n }\n\n this.addMissingColumns(tableName, schema, row);\n\n const columnNames = Object.keys(row);\n const quotedColumns = columnNames.map((col) => this.quoteIdentifier(col));\n const placeholders = columnNames.map(() => '?').join(', ');\n const sql = `INSERT INTO ${this.quoteTableName(tableName)} (${quotedColumns.join(', ')}) VALUES (${placeholders})`;\n\n const values = columnNames.map((col) => this.normalizeValue(row[col], this.columnOf(tableName, col)));\n // After the values: one the database cannot take throws there, with nothing to undo yet\n const undoSettle = this.settleColumnsNoRowHolds(schema, row);\n let result: ReturnType<typeof this.executeInternal>;\n try {\n result = this.executeInternal(sql, values);\n } catch (error) {\n undoSettle();\n throw error;\n }\n if (destination) {\n const origins = this.rowOriginsByRowid.get(tableName) ?? new Map<string, RowOrigin>();\n origins.set(String(result.lastInsertRowid), { file: destination, rowIndex: -1 });\n this.rowOriginsByRowid.set(tableName, origins);\n }\n this.noteFieldChanges(tableName, result.lastInsertRowid, { set: givenFields(data), inserted: true });\n\n // Auto-sync if not in transaction\n this.afterWrite(tableName, result.changes);\n\n return result;\n }\n\n /**\n * A table made from the columns given has only those, and the validator may add a field they lack: the\n * columns of a table made from rows are those of the validated rows, which have it\n */\n private addMissingColumns(tableName: string, schema: TableSchema, row: JsonObject): void {\n if (!this.tablesFromGivenColumns.has(tableName)) return;\n const known = new Set(schema.columns.map((column) => column.name));\n const missing = Object.keys(row).filter((key) => !known.has(key));\n if (missing.length === 0) return;\n for (const column of unwrap(JsonlReader.inferSchema(tableName, [row])).columns) {\n if (!missing.includes(column.name)) continue;\n const sqlType = column.type === 'JSON' ? 'TEXT' : column.type;\n this.db.exec(\n `ALTER TABLE ${this.quoteTableName(tableName)} ADD COLUMN ${this.quoteIdentifier(column.name)} ${sqlType}`,\n );\n schema.columns.push({ name: column.name, type: column.type, notNull: false, valueType: column.valueType });\n }\n }\n\n /**\n * Batch insert rows with validation per record.\n */\n batchInsert<K extends keyof Tables & string>(\n tableName: K,\n records: Tables[K][],\n ): Result<{ changes: number | bigint; lastInsertRowid: number | bigint }, Error> {\n try {\n return ok(this.batchInsertInternal(tableName, records));\n } catch (error) {\n return err(toError(error));\n }\n }\n\n private batchInsertInternal<K extends keyof Tables & string>(\n tableName: K,\n records: Tables[K][],\n ): { changes: number | bigint; lastInsertRowid: number | bigint } {\n this.assertMutable(tableName);\n if (this.hasSeveralDataDirs()) throw new Error('Use insert with a dataDir for data sets');\n\n const schema = this.schemas.get(tableName);\n if (!schema) {\n throw new Error(`Table ${tableName} does not exist`);\n }\n\n if (records.length === 0) {\n return { changes: 0, lastInsertRowid: 0 };\n }\n\n let totalChanges = 0n;\n let lastRowid = 0n;\n\n // Not only once every record went in: the caller may go on after a failed one, keeping those before it\n try {\n for (const record of records) {\n const row = this.validateAndTransform(tableName, record);\n this.addMissingColumns(tableName, schema, row);\n\n const columnNames = Object.keys(row);\n const quotedColumns = columnNames.map((col) => this.quoteIdentifier(col));\n const placeholders = columnNames.map(() => '?').join(', ');\n const sql = `INSERT INTO ${this.quoteTableName(tableName)} (${quotedColumns.join(', ')}) VALUES (${placeholders})`;\n\n const values = columnNames.map((col) => this.normalizeValue(row[col], this.columnOf(tableName, col)));\n const undoSettle = this.settleColumnsNoRowHolds(this.schemas.get(tableName), row);\n\n let result: ReturnType<typeof this.executeInternal>;\n try {\n result = this.executeInternal(sql, values);\n } catch (error) {\n undoSettle();\n throw error;\n }\n this.noteFieldChanges(tableName, result.lastInsertRowid, { set: givenFields(record), inserted: true });\n totalChanges += BigInt(result.changes);\n lastRowid = BigInt(result.lastInsertRowid);\n }\n } finally {\n this.afterWrite(tableName, totalChanges);\n }\n\n return {\n changes: totalChanges,\n lastInsertRowid: lastRowid,\n };\n }\n\n /**\n * Update rows in a table with validation (supports OR/AND with arrays)\n * Note: Function filters are not supported for update operations\n * Note: By default, validation is enabled. For partial updates, existing data is fetched\n * and merged before validation. Set options.validate = false to disable validation.\n */\n update<K extends keyof Tables & string>(\n tableName: K,\n data: Partial<Tables[K]>,\n where: WhereCondition<Tables[K]>,\n options?: UpdateOptions,\n ): Result<{ changes: number | bigint; lastInsertRowid: number | bigint }, Error> {\n try {\n return ok(this.updateInternal(tableName, data, where, options));\n } catch (error) {\n return err(toError(error));\n }\n }\n\n private updateInternal<K extends keyof Tables & string>(\n tableName: K,\n data: Partial<Tables[K]>,\n where: WhereCondition<Tables[K]>,\n options?: UpdateOptions,\n ): { changes: number | bigint; lastInsertRowid: number | bigint } {\n this.assertMutable(tableName);\n\n const schema = this.schemas.get(tableName);\n if (!schema) {\n throw new Error(`Table ${tableName} does not exist`);\n }\n\n // Validate by default (can be disabled with validate: false)\n const shouldValidate = options?.validate !== false;\n const hasValidationSchema = this.validationSchemas.has(tableName);\n\n if (shouldValidate && hasValidationSchema) {\n // Get existing rows to merge with partial data\n const existingRows = this.findInternal(tableName, where);\n\n // Validate each merged row\n for (const existingRow of existingRows) {\n const mergedData: Record<string, unknown> = { ...existingRow, ...data };\n // Not checked with the values the update resets: they are about to be replaced by the schema's\n for (const field of options?.resetToDefault ?? []) delete mergedData[field];\n this.validateData(tableName, mergedData);\n }\n }\n\n const { sql: whereSql, values: whereValues, functionFilters } = this.buildWhereClause(where, tableName);\n\n if (functionFilters.length > 0) {\n throw new Error('Function filters are not supported in update operations');\n }\n\n const targets = this.queryInternal<JsonObject>(\n `SELECT rowid AS \"${ROWID_ALIAS}\", * FROM ${this.quoteTableName(tableName)} WHERE ${whereSql}`,\n whereValues,\n );\n\n // Not computed after the UPDATE: a reset the schema refuses must fail the update before it changes anything\n const resetFields = options?.resetToDefault ?? [];\n const resets =\n resetFields.length > 0 ? this.computeResets(tableName, targets, data as JsonObject, resetFields) : [];\n\n let result: { changes: number | bigint; lastInsertRowid: number | bigint } = { changes: 0, lastInsertRowid: 0 };\n if (Object.keys(data).length > 0) {\n const setClauses = Object.keys(data)\n .map((key) => `${this.quoteIdentifier(key)} = ?`)\n .join(', ');\n const sql = `UPDATE ${this.quoteTableName(tableName)} SET ${setClauses} WHERE ${whereSql}`;\n const values = [\n ...Object.entries(data).map(([key, v]) => this.normalizeValue(v, this.columnOf(tableName, key))),\n ...whereValues,\n ];\n const undoSettle = this.settleColumnsNoRowHolds(this.schemas.get(tableName), data as JsonObject);\n try {\n result = this.executeInternal(sql, values);\n } catch (error) {\n undoSettle();\n throw error;\n }\n if (Number(result.changes) === 0) undoSettle();\n }\n\n const pkName = this.schemas.get(tableName)?.columns.find((col) => col.primaryKey)?.name;\n if (pkName && Object.hasOwn(data, pkName)) {\n // An INTEGER PRIMARY KEY is the rowid, so a new key moves the row, and what is kept by rowid with it\n const moved = this.queryInternal<JsonObject>(\n `SELECT rowid AS \"${ROWID_ALIAS}\" FROM ${this.quoteTableName(tableName)} WHERE ${this.quoteIdentifier(pkName)} = ?`,\n [this.normalizeValue((data as Record<string, unknown>)[pkName], this.columnOf(tableName, pkName))],\n );\n if (targets.length === 1 && moved.length === 1) {\n const from = String(targets[0][ROWID_ALIAS]);\n const to = moved[0][ROWID_ALIAS];\n if (from !== String(to)) {\n this.moveRowMetadata(tableName, from, String(to));\n targets[0] = { ...targets[0], [ROWID_ALIAS]: to };\n }\n }\n }\n\n for (const target of targets) {\n const set = Object.keys(data).filter(\n (key) =>\n !sameStoredValue(\n target[key],\n this.normalizeValue((data as Record<string, unknown>)[key], this.columnOf(tableName, key)),\n ),\n );\n this.noteFieldChanges(tableName, target[ROWID_ALIAS] as number | bigint, { set });\n }\n\n if (resets.length > 0) {\n result = this.applyResets(tableName, resets, resetFields);\n }\n\n // Auto-sync if not in transaction\n this.afterWrite(tableName, result.changes);\n\n return result;\n }\n\n /**\n * Batch update rows with record-specific values and validation.\n * Each record must include the primary key to identify the target row.\n * Validation runs once per merged record unless explicitly disabled.\n */\n batchUpdate<K extends keyof Tables & string>(\n tableName: K,\n records: Array<Partial<Tables[K]> & Record<string, unknown>>,\n options?: { validate?: boolean },\n ): Result<{ changes: number | bigint; lastInsertRowid: number | bigint }, Error> {\n try {\n return ok(this.batchUpdateInternal(tableName, records, options));\n } catch (error) {\n return err(toError(error));\n }\n }\n\n private batchUpdateInternal<K extends keyof Tables & string>(\n tableName: K,\n records: Array<Partial<Tables[K]> & Record<string, unknown>>,\n options?: { validate?: boolean },\n ): { changes: number | bigint; lastInsertRowid: number | bigint } {\n this.assertMutable(tableName);\n\n const schema = this.schemas.get(tableName);\n if (!schema) {\n throw new Error(`Table ${tableName} does not exist`);\n }\n\n if (records.length === 0) {\n return { changes: 0, lastInsertRowid: 0 };\n }\n\n // Get primary key column\n const pkColumn = schema.columns.find((col) => col.primaryKey);\n if (!pkColumn) {\n throw new Error(`Table ${tableName} does not have a primary key`);\n }\n\n const pkName = pkColumn.name;\n\n // Extract primary key values from records\n const pkValues: unknown[] = [];\n for (const record of records) {\n const pkValue = record[pkName];\n if (pkValue === undefined) {\n throw new Error(`Record is missing primary key '${String(pkName)}': ${JSON.stringify(record)}`);\n }\n pkValues.push(pkValue);\n }\n\n // Validate by default (can be disabled with validate: false)\n const shouldValidate = options?.validate !== false;\n const hasValidationSchema = this.validationSchemas.has(tableName);\n\n if (shouldValidate && hasValidationSchema) {\n // Build OR condition to fetch all existing rows at once\n const orCondition = pkValues.map((pkValue) => ({\n [pkName]: pkValue,\n })) as WhereCondition<Tables[K]>;\n\n // Fetch all existing rows in one query\n const existingRows = this.findInternal(tableName, orCondition);\n\n // Create a map for fast lookup: pkValue -> existingRow\n const existingRowsMap = new Map<unknown, Tables[K]>();\n for (const row of existingRows) {\n const pkValue = (row as Record<string, unknown>)[pkName];\n existingRowsMap.set(pkValue, row);\n }\n\n // Validate each merged record and collect all errors\n const validationErrors: Array<{\n rowIndex: number;\n rowData: unknown;\n pkValue: unknown;\n error: ValidationError;\n }> = [];\n\n for (let i = 0; i < records.length; i++) {\n const record = records[i];\n const pkValue = record[pkName];\n const existingRow = existingRowsMap.get(pkValue);\n\n if (!existingRow) {\n throw new Error(`No existing row found with ${String(pkName)}=${JSON.stringify(pkValue)}`);\n }\n\n const mergedData = { ...existingRow, ...record };\n\n try {\n this.validateData(tableName, mergedData);\n } catch (error) {\n // Collect validation errors instead of throwing immediately\n if (error instanceof Error && error.name === 'ValidationError') {\n validationErrors.push({\n rowIndex: i,\n rowData: mergedData,\n pkValue,\n error: error as ValidationError,\n });\n } else {\n throw error;\n }\n }\n }\n\n // If there are validation errors, throw with all error information\n if (validationErrors.length > 0) {\n const enhancedError = new Error(\n `Validation failed for ${validationErrors.length} row(s)`,\n ) as ValidationError & { validationErrors: typeof validationErrors };\n enhancedError.name = 'ValidationError';\n enhancedError.validationErrors = validationErrors;\n // For backward compatibility, include issues from first error\n enhancedError.issues = validationErrors[0].error.issues;\n throw enhancedError;\n }\n }\n\n // All validations passed - perform updates\n let totalChanges = 0n;\n let lastRowid = 0n;\n\n for (const record of records) {\n const pkValue = record[pkName];\n const where = { [pkName]: pkValue } as WhereCondition<Tables[K]>;\n\n // Call update without validation (already validated above)\n const result = this.updateInternal(tableName, record as Partial<Tables[K]>, where, {\n validate: false,\n });\n\n totalChanges += BigInt(result.changes);\n lastRowid = BigInt(result.lastInsertRowid);\n }\n\n return {\n changes: totalChanges,\n lastInsertRowid: lastRowid,\n };\n }\n\n /**\n * Delete rows from a table (supports OR/AND with arrays)\n * Note: Function filters are not supported for delete operations\n */\n delete<K extends keyof Tables & string>(\n tableName: K,\n where: WhereCondition<Tables[K]>,\n ): Result<{ changes: number | bigint; lastInsertRowid: number | bigint }, Error> {\n try {\n return ok(this.deleteInternal(tableName, where));\n } catch (error) {\n return err(toError(error));\n }\n }\n\n private deleteInternal<K extends keyof Tables & string>(\n tableName: K,\n where: WhereCondition<Tables[K]>,\n ): { changes: number | bigint; lastInsertRowid: number | bigint } {\n this.assertMutable(tableName);\n\n const schema = this.schemas.get(tableName);\n if (!schema) {\n throw new Error(`Table ${tableName} does not exist`);\n }\n\n const { sql: whereSql, values, functionFilters } = this.buildWhereClause(where, tableName);\n\n if (functionFilters.length > 0) {\n throw new Error('Function filters are not supported in delete operations');\n }\n\n const deleted = this.rowidsWhere(tableName, whereSql, values);\n const sql = `DELETE FROM ${this.quoteTableName(tableName)} WHERE ${whereSql}`;\n const result = this.executeInternal(sql, values);\n this.forgetFieldChanges(tableName, deleted);\n\n // Auto-sync if not in transaction\n this.afterWrite(tableName, result.changes);\n\n return result;\n }\n\n /**\n * Batch delete rows by primary key.\n */\n batchDelete<K extends keyof Tables & string>(\n tableName: K,\n records: Array<Partial<Tables[K]> & Record<string, unknown>>,\n ): Result<{ changes: number | bigint; lastInsertRowid: number | bigint }, Error> {\n try {\n return ok(this.batchDeleteInternal(tableName, records));\n } catch (error) {\n return err(toError(error));\n }\n }\n\n private batchDeleteInternal<K extends keyof Tables & string>(\n tableName: K,\n records: Array<Partial<Tables[K]> & Record<string, unknown>>,\n ): { changes: number | bigint; lastInsertRowid: number | bigint } {\n this.assertMutable(tableName);\n\n const schema = this.schemas.get(tableName);\n if (!schema) {\n throw new Error(`Table ${tableName} does not exist`);\n }\n\n if (records.length === 0) {\n return { changes: 0, lastInsertRowid: 0 };\n }\n\n const pkColumn = schema.columns.find((col) => col.primaryKey);\n if (!pkColumn) {\n throw new Error(`Table ${tableName} does not have a primary key`);\n }\n const pkName = pkColumn.name;\n\n const pkValues = records.map((record, index) => {\n const pkValue = record[pkName as keyof Tables[K]];\n if (pkValue === undefined) {\n throw new Error(`Record at index ${index} is missing primary key '${String(pkName)}'`);\n }\n return pkValue;\n });\n\n const placeholders = pkValues.map(() => '?').join(', ');\n const sql = `DELETE FROM ${this.quoteTableName(tableName)} WHERE ${this.quoteIdentifier(pkName)} IN (${placeholders})`;\n const values = pkValues.map((value) => this.normalizeValue(value, this.columnOf(tableName, pkName)));\n const deleted = this.rowidsWhere(tableName, `${this.quoteIdentifier(pkName)} IN (${placeholders})`, values);\n const result = this.executeInternal(sql, values);\n this.forgetFieldChanges(tableName, deleted);\n\n this.afterWrite(tableName, result.changes);\n\n return {\n changes: BigInt(result.changes),\n lastInsertRowid: BigInt(result.lastInsertRowid),\n };\n }\n\n /**\n * Normalize value for SQLite\n */\n private normalizeValue(value: unknown, column?: { type: string }): string | number | bigint | null | Uint8Array {\n if (value === null || value === undefined) return null;\n // A JSON column holds JSON text for every value, a string quoted, so that reading it back with JSON.parse gives the type it had\n if (column?.type === 'JSON') {\n if (value instanceof Uint8Array) return value;\n return typeof value === 'bigint' ? value.toString() : JSON.stringify(value);\n }\n if (typeof value === 'boolean') return value ? 1 : 0;\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'bigint') return value;\n if (value instanceof Uint8Array) return value;\n // For objects, convert to JSON string\n return JSON.stringify(value);\n }\n\n private columnOf(tableName: string, columnName: string): { type: string } | undefined {\n return this.schemas.get(tableName)?.columns.find((column) => column.name === columnName);\n }\n\n /**\n * Build WHERE clause from condition (supports OR/AND with arrays and functions)\n */\n private buildWhereClause<T extends Record<string, unknown>>(\n condition: WhereCondition<T>,\n tableName: string,\n ): {\n sql: string;\n values: Array<string | number | bigint | null | Uint8Array>;\n functionFilters: Array<{\n key: string;\n fn: (value: unknown) => boolean;\n }>;\n hasOrWithFunctionFilters: boolean;\n } {\n const values: Array<string | number | bigint | null | Uint8Array> = [];\n const functionFilters: Array<{ key: string; fn: (value: unknown) => boolean }> = [];\n let hasOrWithFunctionFilters = false;\n\n const buildCondition = (cond: WhereCondition<T>, isInOr = false): string => {\n // Handle array (OR conditions)\n if (Array.isArray(cond)) {\n const clauses = cond\n .map((item) => {\n const clause = Array.isArray(item) ? buildCondition(item, true) : buildCondition(item, true);\n return clause ? `(${clause})` : '';\n })\n .filter((clause) => clause !== ''); // Filter out empty clauses\n\n return clauses.join(' OR ');\n }\n\n // Handle object (AND conditions)\n const conditions: string[] = [];\n let hasFunctionFilter = false;\n for (const [key, value] of Object.entries(cond)) {\n if (typeof value === 'function') {\n // Function filter - will be applied later\n functionFilters.push({ key, fn: value as (value: unknown) => boolean });\n hasFunctionFilter = true;\n } else {\n // Regular value\n conditions.push(`${this.quoteIdentifier(key)} = ?`);\n values.push(this.normalizeValue(value, this.columnOf(tableName, key)));\n }\n }\n\n if (isInOr && hasFunctionFilter) {\n hasOrWithFunctionFilters = true;\n }\n\n return conditions.join(' AND ');\n };\n\n const sql = buildCondition(condition);\n return { sql, values, functionFilters, hasOrWithFunctionFilters };\n }\n\n /**\n * Apply OR condition with function filters by evaluating each row against the condition\n */\n private applyOrConditionWithFilters<T extends Record<string, unknown>>(rows: T[], condition: WhereCondition<T>): T[] {\n return rows.filter((row) => this.matchesOrCondition(row, condition));\n }\n\n /**\n * Check if a row matches an OR/AND condition (recursively)\n */\n private matchesOrCondition<T extends Record<string, unknown>>(row: T, condition: WhereCondition<T>): boolean {\n // Handle array (OR conditions)\n if (Array.isArray(condition)) {\n return condition.some((item) => this.matchesOrCondition(row, item));\n }\n\n // Handle object (AND conditions)\n return Object.entries(condition).every(([key, value]) => {\n const rowValue = row[key as keyof T];\n if (typeof value === 'function') {\n return (value as (value: unknown) => boolean)(rowValue);\n }\n return rowValue === value;\n });\n }\n\n /**\n * Apply function filters to rows\n */\n private applyFunctionFilters<T extends Record<string, unknown>>(\n rows: T[],\n functionFilters: Array<{ key: string; fn: (value: unknown) => boolean }>,\n ): T[] {\n if (functionFilters.length === 0) return rows;\n\n return rows.filter((row) => {\n return functionFilters.every(({ key, fn }) => {\n const value = row[key as keyof T];\n return fn(value);\n });\n });\n }\n\n /**\n * Get table schema\n */\n /**\n * Validate a row against a table's schema, also for a table left out on load because rows failed\n * validation, so a fix can be checked before it is written to the file\n */\n validateRow(tableName: string, row: JsonObject): Result<JsonObject, ValidationError> {\n // A table left out on load is not among the tables, but its schema was loaded\n if (!this.tables.has(tableName) && !this.validationSchemas.has(tableName)) {\n const error = new Error(`Table '${tableName}' does not exist`) as ValidationError;\n error.name = 'ValidationError';\n error.issues = [{ message: `Table '${tableName}' does not exist` }];\n return err(error);\n }\n try {\n return ok(this.validateAndTransform(tableName, row));\n } catch (error) {\n if (error instanceof Error && error.name === 'ValidationError') return err(error as ValidationError);\n throw error;\n }\n }\n\n getSchema(tableName: string): TableSchema | undefined {\n return this.schemas.get(tableName);\n }\n\n /**\n * Get all table names\n */\n getTableNames(): string[] {\n return Array.from(this.schemas.keys());\n }\n\n /**\n * A database composed from several data directories is read-only: the rows of its tables have no\n * single file to be written back to\n */\n private hasSeveralDataDirs(): boolean {\n return typeof this.config.dataDir !== 'string' && this.config.dataDir.length > 1;\n }\n\n /**\n * Turn query_only back on before running a caller's SQL, since an earlier call may have run\n * `PRAGMA query_only = OFF`\n */\n /**\n * Refuse SQL that would end a transaction() or lift the read-only mode that holds back writes made\n * through the database while it runs. Looked for in each statement as SQLite reads it, so a `;` or a\n * comment cannot hide one\n */\n private refuseUnsafeSql(sql: string, viaTransaction = this.viaTransactionObject): void {\n if (\n this.hasSeveralDataDirs() &&\n this.config.writeDataSets &&\n splitStatements(sql).some((statement) => !isReadOnlyStatement(statement))\n ) {\n throw new Error(\n 'Raw SQL is read-only for composed data sets; use insert, update, or delete to preserve source routing',\n );\n }\n // Not only once begun: the read-only mode is held from the moment a transaction starts until it closes,\n // and a BEGIN while it starts would make its own BEGIN fail with one left open that it never rolls back\n if (!this.inTransaction && !this.transactionStarting && !this.transactionClosing) return;\n for (const statement of splitStatements(sql)) {\n // Closed by default: SQL run through the database while a transaction runs may only read, as any\n // other statement or pragma could change the transaction, and none can be listed one by one\n if (this.inTransaction && !viaTransaction && !isReadOnlyStatement(statement)) {\n throw new Error(\n `'${sql.trim()}' is not a read: while a transaction runs, SQL that changes anything must go through the callback's tx`,\n );\n }\n if (/^(BEGIN|COMMIT|END|ROLLBACK(?!\\s+(TRANSACTION\\s+)?TO\\b))\\b/i.test(statement)) {\n throw new Error(\n `'${sql.trim()}' would end the transaction before its files are written back; return from the callback to commit, or throw to roll back`,\n );\n }\n // Not once begun, when a SAVEPOINT is a transaction nested in it and does no harm\n if (!this.inTransaction && /^SAVEPOINT\\b/i.test(statement)) {\n throw new Error(`'${sql.trim()}' would open a transaction of its own while the transaction starts`);\n }\n // Only setting it: reading the pragma changes nothing, and reads through the database stay available\n if (\n /^PRAGMA\\s+(?:(?:\\w+|\"[^\"]*\"|'[^']*'|`[^`]*`|\\[[^\\]]*\\])\\s*\\.\\s*)?(?:query_only|\"query_only\"|'query_only'|`query_only`|\\[query_only\\])\\s*[=(]/i.test(\n statement,\n )\n ) {\n throw new Error(\n `'${sql.trim()}' would lift the read-only mode that refuses writes made while a transaction runs`,\n );\n }\n }\n }\n\n private isReadOnlyDataSet(): boolean {\n return this.hasSeveralDataDirs() && !this.config.writeDataSets;\n }\n\n private enforceReadOnlySql(): void {\n if (this.isReadOnlyDataSet()) {\n this.db.exec('PRAGMA query_only = ON');\n }\n }\n\n /** Writable, and not while a transaction writes back the rows it has already read */\n private assertMutable(tableName: string): void {\n this.assertWritable(tableName);\n this.refuseWhileTransactionSettles(`write to table '${tableName}'`);\n }\n\n /**\n * Refuse a change while a transaction starts or writes its files back: one made while it starts would\n * be written back with rows the transaction may roll back, and one made while it closes would be\n * committed without reaching the files. Also refuse one made through the database itself while the\n * callback runs, which would be committed or rolled back with the transaction unnoticed by its caller\n */\n private refuseWhileTransactionSettles(action: string, viaTransaction = this.viaTransactionObject): void {\n if (this.inTransaction && !viaTransaction) {\n throw new Error(\n `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`,\n );\n }\n if (this.transactionStarting) {\n throw new Error(`Cannot ${action} while a transaction is starting; ${action.split(' ')[0]} once it has finished`);\n }\n if (this.transactionClosing) {\n throw new Error(\n `Cannot ${action} while a transaction writes its files back; ${action.split(' ')[0]} once it has finished`,\n );\n }\n }\n\n /**\n * Run a query() with the database read-only while a transaction starts or writes its files back.\n * Not refused outright as execute() is: a query that only reads changes nothing the files would miss\n */\n private readOnlyWhileTransactionSettles<T>(run: () => T, viaTransaction = this.viaTransactionObject): T {\n if (\n !this.hasSeveralDataDirs() &&\n !this.transactionStarting &&\n !this.transactionClosing &&\n !(this.inTransaction && !viaTransaction)\n ) {\n return run();\n }\n this.db.exec('PRAGMA query_only = ON');\n try {\n return run();\n } catch (error) {\n if (/readonly/i.test(toError(error).message)) this.refuseWhileTransactionSettles('change rows', viaTransaction);\n throw error;\n } finally {\n if (!this.isReadOnlyDataSet()) this.db.exec('PRAGMA query_only = OFF');\n }\n }\n\n private assertWritable(tableName?: string): void {\n if (this.isReadOnlyDataSet()) {\n const target = tableName ? `table '${tableName}'` : 'the database';\n throw new Error(\n `Cannot write to ${target}: dataDir lists several directories, so its rows have no single file to be written back to`,\n );\n }\n }\n\n /**\n * Sync a specific table back to its JSONL file\n * Syncs of the same table run one after another: auto-sync is fire-and-forget, and a write-back\n * that reads the file first must never see a file another sync is halfway through writing.\n */\n private async syncTable(tableName: string, options?: InternalSyncOptions): Promise<void> {\n const pending = this.syncQueue.get(tableName) ?? Promise.resolve();\n const current = pending.then(() => this.writeTable(tableName, options));\n\n this.syncQueue.set(\n tableName,\n current.catch(() => {}),\n );\n\n return current;\n }\n\n /**\n * Write a table back to its JSONL file\n * Uses backward transformation when available\n */\n private async writeTable(tableName: string, options?: InternalSyncOptions): Promise<void> {\n await this.writeFilesTogether(await this.prepareWriteBack(tableName, options));\n }\n\n /**\n * The rows a table is written back as, laid over the lines of its file; fails when the file changed\n * since this database last read or wrote it\n */\n private async prepareWriteBack(tableName: string, options?: InternalSyncOptions): Promise<PreparedWriteBack[]> {\n this.assertWritable(tableName);\n const config = this.tables.get(tableName);\n if (!config) throw new Error(`Table ${tableName} not found`);\n const stored = this.readStoredRows(tableName);\n if (!this.hasSeveralDataDirs()) {\n return [await this.prepareFileWriteBack(tableName, config.jsonlPath, stored, options)];\n }\n const origins = this.rowOriginsByRowid.get(tableName);\n const byFile = new Map<string, number[]>(\n [this.config.dataDir].flat().map((dir) => [join(dir, `${tableName}.jsonl`), []]),\n );\n stored.rowids.forEach((rowid, index) => {\n const origin = origins?.get(rowid);\n if (!origin) throw new Error(`Row ${rowid} of '${tableName}' has no data directory; insert with a dataDir`);\n const indexes = byFile.get(origin.file) ?? [];\n indexes.push(index);\n byFile.set(origin.file, indexes);\n });\n const prepared: PreparedWriteBack[] = [];\n for (const [file, indexes] of byFile) {\n indexes.sort(\n (a, b) =>\n (origins!.get(stored.rowids[a])!.rowIndex < 0 ? Infinity : origins!.get(stored.rowids[a])!.rowIndex) -\n (origins!.get(stored.rowids[b])!.rowIndex < 0 ? Infinity : origins!.get(stored.rowids[b])!.rowIndex),\n );\n const rows = {\n rowids: indexes.map((i) => stored.rowids[i]),\n rows: indexes.map((i) => stored.rows[i]),\n lineRows: indexes.map((i) => stored.lineRows[i]),\n };\n const fileWrite = await this.prepareFileWriteBack(tableName, file, rows, options);\n if (!fileWrite.unchanged) prepared.push(fileWrite);\n }\n return prepared;\n }\n\n private async prepareFileWriteBack(\n tableName: string,\n jsonlPath: string,\n stored: ReturnType<LinesDB<Tables>['readStoredRows']>,\n options?: InternalSyncOptions,\n ): Promise<PreparedWriteBack> {\n const { rowids, rows: deserializedRows, lineRows } = stored;\n const generation = this.changeGenerations.get(tableName) ?? 0;\n let finalRows = lineRows;\n const previousContent = await readFile(jsonlPath, 'utf-8').catch((error: NodeJS.ErrnoException) => {\n if (error.code === 'ENOENT') return undefined;\n throw error;\n });\n const existingRows = await this.readUnchangedRows(jsonlPath);\n\n const matches = this.hasSeveralDataDirs()\n ? rowids.map((rowid) => existingRows[this.rowOriginsByRowid.get(tableName)!.get(rowid)!.rowIndex])\n : undefined;\n\n // An empty list means no field is written back, not that every field is\n const fields = options?.fields ?? this.config.writeBackFields;\n if ((options?.writeFilledValues ?? this.config.writeFilledValues ?? 'all') === 'primaryKey') {\n finalRows = this.keepWrittenFields(\n tableName,\n rowids,\n deserializedRows,\n finalRows,\n existingRows,\n fields,\n matches,\n ).map(({ written }) => written);\n }\n // Not added before narrowing: a field the line holds that the row lacks reads as a renamed one there\n const columns = new Set(this.schemas.get(tableName)?.columns.map((column) => column.name));\n const readLines = this.linesWithUnknownFields.get(tableName);\n finalRows = finalRows.map((row, index) => {\n const line = readLines?.get(rowids[index]);\n return line ? keepUnknownFields(line, row, columns) : row;\n });\n finalRows = this.mergeWithExistingLines(tableName, existingRows, finalRows, {\n fields,\n strictFields: options?.strictFields ?? false,\n matches,\n });\n\n return {\n tableName,\n jsonlPath,\n rows: finalRows,\n previousContent,\n generation,\n ...(matches\n ? { rowids, unchanged: JsonlWriter.serialize(existingRows) === JsonlWriter.serialize(finalRows) }\n : {}),\n };\n }\n\n /**\n * Every row of a table in rowid order - the order the file was read in - as stored and as its line\n * would hold it, after the backward transformation\n */\n private readStoredRows(tableName: string): { rowids: string[]; rows: JsonObject[]; lineRows: JsonObject[] } {\n const stored = this.queryInternal<JsonObject>(\n `SELECT rowid AS \"${ROWID_ALIAS}\", * FROM ${this.quoteTableName(tableName)} ORDER BY rowid`,\n );\n const rowids = stored.map((row) => String(row[ROWID_ALIAS]));\n const rows = stored.map(({ [ROWID_ALIAS]: _rowid, ...row }) => this.deserializeRow(tableName, row));\n\n const validationSchema = this.validationSchemas.get(tableName);\n const lineRows =\n validationSchema && hasBackward(validationSchema)\n ? rows.map((row) => (validationSchema as BiDirectionalSchema<Table, Table>).backward!(row) as JsonObject)\n : rows;\n return { rowids, rows, lineRows };\n }\n\n /**\n * Narrow each row to the fields a user wrote - the ones its line holds, plus those set since and\n * minus those reset to their default - its primary key and the fields named to be written back, so\n * a value the schema fills in stays out of the file\n */\n private keepWrittenFields(\n tableName: string,\n rowids: string[],\n rows: JsonObject[],\n lineRows: JsonObject[],\n existingRows: JsonObject[],\n namedFields: readonly string[] = [],\n matchedLines?: Array<JsonObject | undefined>,\n ): Array<{ written: JsonObject; narrowed: boolean }> {\n const pkName = this.schemas.get(tableName)?.columns.find((col) => col.primaryKey)?.name;\n // Not left to the recorded changes: an ON DELETE / ON UPDATE action changes these columns in SQLite\n // without a write through this database\n const actionColumns = (this.schemas.get(tableName)?.foreignKeys ?? [])\n .filter((fk) => [fk.onDelete, fk.onUpdate].some((action) => action === 'CASCADE' || action === 'SET NULL'))\n .map((fk) => fk.column);\n const lines = matchedLines ?? this.matchExistingRows(tableName, lineRows, existingRows, { required: false });\n const changes = this.fieldChanges.get(tableName);\n\n return lineRows.map((lineRow, index) => {\n const line = lines?.[index];\n const rowChanges = changes?.get(rowids[index]);\n // Not narrowed when the backward transformation renames fields: the line's keys name other fields\n const renamesFields = Object.keys(lineRow).some((key) => !Object.hasOwn(rows[index], key));\n // Not narrowed without a line unless the row was inserted: a row whose key changed has lost its\n // line too, and narrowing it would drop the fields that line held\n if (renamesFields || this.rawSqlTables.has(tableName) || (!line && !rowChanges?.inserted)) {\n return { written: lineRow, narrowed: false };\n }\n\n const keep = new Set([...Object.keys(line ?? {}), ...(rowChanges?.set ?? []), ...actionColumns]);\n for (const key of rowChanges?.reset ?? []) keep.delete(key);\n for (const key of namedFields) keep.add(key);\n if (pkName) keep.add(pkName);\n // Not the stored value for a row nothing wrote to: a schema computes a value that may differ from what\n // the line holds, and an edit elsewhere in the file is no reason to write it into this line\n const untouched = line !== undefined && !rowChanges?.inserted && !rowChanges?.set.size && !rowChanges?.reset.size;\n return {\n written: Object.fromEntries(\n Object.entries(lineRow)\n .filter(([key]) => keep.has(key))\n .map(([key, value]) => [\n key,\n untouched && Object.hasOwn(line, key) && !actionColumns.includes(key) && !namedFields.includes(key)\n ? line[key]\n : value,\n ]),\n ) as JsonObject,\n narrowed: true,\n };\n });\n }\n\n private rowidsWhere(\n tableName: string,\n whereSql: string,\n values: (string | number | bigint | null | Uint8Array)[],\n ): string[] {\n return this.queryInternal<JsonObject>(\n `SELECT rowid AS \"${ROWID_ALIAS}\" FROM ${this.quoteTableName(tableName)} WHERE ${whereSql}`,\n values,\n ).map((row) => String(row[ROWID_ALIAS]));\n }\n\n /**\n * Forget the field changes of deleted rows: a deleted row's rowid can be given to a row inserted\n * later, which must not inherit them\n */\n private moveRowMetadata(tableName: string, from: string, to: string): void {\n for (const byRow of [\n this.fieldChanges.get(tableName),\n this.linesWithUnknownFields.get(tableName),\n this.rowOriginsByRowid.get(tableName),\n ]) {\n const kept = byRow?.get(from);\n if (!byRow || kept === undefined) continue;\n byRow.delete(from);\n byRow.set(to, kept as never);\n }\n }\n\n /** Forget the lines kept for rows that are gone, such as rows raw SQL or a foreign-key action deleted */\n private forgetLinesOfGoneRows(tableNames: Iterable<string>): void {\n for (const tableName of tableNames) {\n const lines = this.linesWithUnknownFields.get(tableName);\n if (!lines || lines.size === 0) continue;\n let stored: JsonObject[];\n try {\n stored = this.queryInternal<JsonObject>(\n `SELECT rowid AS \"${ROWID_ALIAS}\" FROM ${this.quoteTableName(tableName)}`,\n );\n } catch {\n // Not thrown: raw SQL may have dropped the table, and the error worth reporting is that SQL's own\n continue;\n }\n const present = new Set(stored.map((row) => String(row[ROWID_ALIAS])));\n for (const rowid of lines.keys()) if (!present.has(rowid)) lines.delete(rowid);\n }\n }\n\n private forgetFieldChanges(tableName: string, rowids: string[]): void {\n for (const rowid of rowids) {\n this.fieldChanges.get(tableName)?.delete(rowid);\n this.linesWithUnknownFields.get(tableName)?.delete(rowid);\n }\n }\n\n private noteChange(tableName: string): void {\n this.changeGenerations.set(tableName, (this.changeGenerations.get(tableName) ?? 0) + 1);\n }\n\n private noteFieldChanges(\n tableName: string,\n rowid: number | bigint,\n changes: { set?: readonly string[]; reset?: readonly string[]; inserted?: boolean },\n ): void {\n this.noteChange(tableName);\n const byRow = this.fieldChanges.get(tableName) ?? new Map<string, FieldChanges>();\n const rowChanges = byRow.get(String(rowid)) ?? {\n set: new Set<string>(),\n reset: new Set<string>(),\n inserted: false,\n };\n if (changes.inserted) rowChanges.inserted = true;\n for (const key of changes.set ?? []) {\n rowChanges.set.add(key);\n rowChanges.reset.delete(key);\n }\n for (const key of changes.reset ?? []) {\n rowChanges.reset.add(key);\n rowChanges.set.delete(key);\n }\n byRow.set(String(rowid), rowChanges);\n this.fieldChanges.set(tableName, byRow);\n }\n\n /**\n * Store the value the schema fills in for each reset field, as validating the row without the field\n * gives it, and remember the field as reset so it leaves the line\n */\n /** The value the schema fills in for each reset field of each target, validating the row without them */\n private computeResets(\n tableName: string,\n targets: JsonObject[],\n data: JsonObject,\n fields: readonly string[],\n ): Array<{ rowid: number | bigint; values: ReturnType<LinesDB<Tables>['normalizeValue']>[] }> {\n return targets.map((target) => {\n const { [ROWID_ALIAS]: rowid, ...stored } = target;\n const row = { ...this.deserializeRow(tableName, stored), ...data };\n for (const field of fields) delete row[field];\n const validated = this.validateAndTransform(tableName, row);\n return {\n rowid: rowid as number | bigint,\n values: fields.map((field) => this.normalizeValue(validated[field], this.columnOf(tableName, field))),\n };\n });\n }\n\n /** Store the values computeResets gave, and remember the fields as reset so they leave the line */\n private applyResets(\n tableName: string,\n resets: Array<{ rowid: number | bigint; values: ReturnType<LinesDB<Tables>['normalizeValue']>[] }>,\n fields: readonly string[],\n ): { changes: number | bigint; lastInsertRowid: number | bigint } {\n let changes = 0n;\n const setClauses = fields.map((field) => `${this.quoteIdentifier(field)} = ?`).join(', ');\n for (const { rowid, values } of resets) {\n const result = this.executeInternal(\n `UPDATE ${this.quoteTableName(tableName)} SET ${setClauses} WHERE rowid = ?`,\n [...values, rowid],\n );\n changes += BigInt(result.changes);\n this.noteFieldChanges(tableName, rowid, { reset: fields });\n }\n return { changes, lastInsertRowid: 0 };\n }\n\n /**\n * Every row of a table with the fields the schema filled in rather than the file: the ones its line\n * does not hold and no write set, which a write-back leaves out of the file\n */\n async findWithDefaults<K extends keyof Tables & string>(\n tableName: K,\n ): Promise<Result<Array<{ row: Tables[K]; defaulted: string[] }>, Error>> {\n try {\n const tableConfig = this.tables.get(tableName);\n if (!tableConfig || !this.schemas.has(tableName)) {\n throw new Error(`Table '${tableName}' is not loaded`);\n }\n // Not read as the file is now: lines another tool changed would be matched to the rows read before\n await this.waitForPendingSyncs();\n const { rowids, rows, lineRows } = this.readStoredRows(tableName);\n const fileRows = new Map<string, JsonObject[]>();\n for (const file of this.hasSeveralDataDirs()\n ? new Set([\n ...(tableConfig.jsonlPaths ?? [tableConfig.jsonlPath]),\n ...[...(this.rowOriginsByRowid.get(tableName)?.values() ?? [])].map((origin) => origin.file),\n ])\n : [tableConfig.jsonlPath]) {\n fileRows.set(file, await this.readUnchangedRows(file));\n }\n const existingRows = [...fileRows.values()].flat();\n const matches =\n this.hasSeveralDataDirs() && this.config.writeDataSets\n ? rowids.map((rowid) => {\n const origin = this.rowOriginsByRowid.get(tableName)?.get(rowid);\n return origin && fileRows.get(origin.file)?.[origin.rowIndex];\n })\n : undefined;\n const kept = this.keepWrittenFields(\n tableName,\n rowids,\n rows,\n lineRows,\n existingRows,\n this.config.writeBackFields,\n matches,\n );\n return ok(\n rows.map((row, index) => ({\n row: row as Tables[K],\n defaulted: kept[index].narrowed\n ? Object.keys(row).filter((key) => !Object.hasOwn(kept[index].written, key))\n : [],\n })),\n );\n } catch (error) {\n return err(toError(error));\n }\n }\n\n private async writePrepared(prepared: PreparedWriteBack): Promise<void> {\n const { jsonlPath, rows, previousContent } = prepared;\n if (this.hasSeveralDataDirs() || this.config.writeDataSets) {\n await replaceFile(jsonlPath, (temporary) => JsonlWriter.write(temporary, rows), previousContent);\n } else {\n await JsonlWriter.write(jsonlPath, rows);\n }\n prepared.completed = true;\n const contentHash = hashJsonlContent(JsonlWriter.serialize(rows));\n this.fileHashes.set(jsonlPath, contentHash);\n this.observedHashes.set(jsonlPath, contentHash);\n }\n\n /**\n * Write a table back to its file, or leave it to the running transaction, which writes back the\n * tables it changed once its callback is done\n */\n private afterWrite(tableName: string, changes: number | bigint): void {\n // Not counted when no row changed: writing the table back could then fail on a file it never touched\n if (BigInt(changes) === 0n && this.transactionChanges) return;\n const tableNames = [tableName, ...this.tablesChangedByForeignKeyActions(tableName)];\n // Not left to the write-back: a row inserted before it can take the rowid of a row deleted here\n this.forgetLinesOfGoneRows(tableNames);\n if (this.transactionChanges) {\n if (this.transactionChanges !== 'all') for (const name of tableNames) this.transactionChanges.add(name);\n return;\n }\n for (const name of tableNames) {\n this.syncTable(name).catch((err) => {\n console.error(`Failed to sync table ${name}:`, err);\n });\n }\n }\n\n /**\n * The tables whose rows an ON DELETE / ON UPDATE action can change when a table's rows change,\n * following the actions on to the tables they change in turn\n */\n private tablesChangedByForeignKeyActions(tableName: string): string[] {\n const found = new Set<string>();\n const visit = (referenced: string) => {\n for (const [name, schema] of this.schemas) {\n if (found.has(name) || name === tableName) continue;\n const acts = (schema.foreignKeys ?? []).some(\n (fk) =>\n fk.references.table === referenced &&\n [fk.onDelete, fk.onUpdate].some((action) => action === 'CASCADE' || action === 'SET NULL'),\n );\n if (acts) {\n found.add(name);\n visit(name);\n }\n }\n };\n visit(tableName);\n return Array.from(found);\n }\n\n private tablesChangedInTransaction(): string[] {\n const changes = this.transactionChanges;\n return changes === 'all' ? Array.from(this.schemas.keys()) : Array.from(changes ?? []);\n }\n\n /**\n * Write several tables back, checking every file before writing any, so a file changed on disk\n * fails the write-back before it has written part of it\n */\n private async writeBackTogether(tableNames: string[]): Promise<PreparedWriteBack[]> {\n await this.waitForPendingSyncs();\n const prepared = [];\n for (const tableName of tableNames) {\n prepared.push(...(await this.prepareWriteBack(tableName)));\n }\n return this.writeFilesTogether(prepared);\n }\n\n private async writeFilesTogether(prepared: PreparedWriteBack[]): Promise<PreparedWriteBack[]> {\n const written: PreparedWriteBack[] = [];\n try {\n for (const table of prepared) {\n // Counted as written before the write: a write that fails can still have truncated the file\n written.push(table);\n await this.writePrepared(table);\n }\n } catch (error) {\n throw await this.restoreAll(written, error);\n }\n for (const { tableName, jsonlPath, generation, rowids } of written) {\n if ((this.changeGenerations.get(tableName) ?? 0) === generation) {\n this.fieldChanges.delete(tableName);\n this.rawSqlTables.delete(tableName);\n }\n if (rowids) {\n const origins = this.rowOriginsByRowid.get(tableName)!;\n rowids.forEach((rowid, rowIndex) => origins.set(rowid, { file: jsonlPath, rowIndex }));\n if (!this.scannedJsonlFiles.includes(jsonlPath)) this.scannedJsonlFiles.push(jsonlPath);\n }\n }\n return written;\n }\n\n /**\n * Put back every written file, going on past one that cannot be put back, and give the error to\n * throw: the one that made the write-back fail, naming the files left holding what was written\n */\n private async restoreAll(written: PreparedWriteBack[], error: unknown): Promise<unknown> {\n const notRestored: string[] = [];\n for (const table of written) {\n await this.restorePrepared(table).catch(() => notRestored.push(table.jsonlPath));\n }\n if (notRestored.length === 0) return error;\n const failure = toError(error);\n const recoveryError = new Error(\n `${failure.message}\\nThese files could not be put back and hold rows the database does not: ${notRestored.join(', ')}`,\n { cause: error },\n );\n if (failure.name === 'JsonlConflictError') {\n recoveryError.name = failure.name;\n (recoveryError as JsonlConflictError).file = (failure as JsonlConflictError).file;\n }\n return recoveryError;\n }\n\n /**\n * Put back the content a file held before {@link writePrepared} wrote over it. The file is expected\n * to hold that content even when putting it back fails, so a file left holding the written rows\n * counts as changed on disk instead of matching the database\n */\n private async restorePrepared({ jsonlPath, previousContent, rows, completed }: PreparedWriteBack): Promise<void> {\n if (this.hasSeveralDataDirs() || this.config.writeDataSets) {\n if (!completed) return;\n const current = await readFile(jsonlPath, 'utf8').catch((error: NodeJS.ErrnoException) => {\n if (error.code === 'ENOENT') return undefined;\n throw error;\n });\n const expected = JsonlWriter.serialize(rows);\n if (current !== expected) throw new Error(`JSONL file '${jsonlPath}' changed during rollback`);\n }\n if (previousContent === undefined) {\n this.fileHashes.delete(jsonlPath);\n this.observedHashes.delete(jsonlPath);\n if (this.hasSeveralDataDirs() || this.config.writeDataSets)\n await replaceFile(jsonlPath, undefined, JsonlWriter.serialize(rows));\n else await rm(jsonlPath, { force: true });\n return;\n }\n this.fileHashes.set(jsonlPath, hashJsonlContent(previousContent));\n this.observedHashes.set(jsonlPath, hashJsonlContent(previousContent));\n if (this.hasSeveralDataDirs() || this.config.writeDataSets) {\n await replaceFile(\n jsonlPath,\n (temporary) => writeFile(temporary, previousContent, 'utf8'),\n JsonlWriter.serialize(rows),\n );\n } else {\n await writeFile(jsonlPath, previousContent, 'utf-8');\n }\n }\n\n /**\n * Lay the rows out over the lines the JSONL file already holds.\n *\n * Rows keep the order the file lists them in - the database returns rows in its own order, and\n * an integer primary key is SQLite's rowid, so writing rows back in query order would reshuffle\n * the file. Rows the file never had follow, in database order.\n *\n * With `fields`, only those fields are taken from the row and every other field keeps the value\n * its line already had, so values a validation hook computed and fields the file omitted are\n * never materialized. Fields this table does not have are simply not written, so one list can\n * cover a directory of tables that do not all share it; a sync asked for a single table by name\n * rejects them instead, since there the caller named both the table and the fields.\n */\n private mergeWithExistingLines(\n tableName: string,\n existingRows: JsonObject[],\n rows: JsonObject[],\n options: { fields?: readonly string[]; strictFields: boolean; matches?: Array<JsonObject | undefined> },\n ): JsonObject[] {\n if (rows.length === 0) {\n return rows;\n }\n\n const { fields } = options;\n const tableFields = fields?.filter((field) => rows.some((row) => field in row));\n if (fields && tableFields && options.strictFields && tableFields.length < fields.length) {\n const unknownFields = fields.filter((field) => !tableFields.includes(field));\n throw new Error(\n `Cannot write back field(s) [${unknownFields.join(', ')}] for table '${tableName}': ` +\n `no such field in the rows written back to the file.`,\n );\n }\n\n // Without `fields` the rows are written whole, so matching them to their line only decides the\n // order: fall back to database order rather than failing when they cannot be matched\n const existing =\n options.matches ?? this.matchExistingRows(tableName, rows, existingRows, { required: fields !== undefined });\n if (!existing) {\n return rows;\n }\n\n const rowByLine = new Map<JsonObject, JsonObject>();\n const newRows: JsonObject[] = [];\n rows.forEach((row, index) => {\n const base = existing[index];\n if (base) {\n rowByLine.set(base, row);\n } else {\n newRows.push(row);\n }\n });\n\n const writtenRows = existingRows\n .filter((base) => rowByLine.has(base))\n .map((base) => {\n const row = rowByLine.get(base)!;\n // A row missing a named field - a backward transformation can drop it - keeps what the file\n // holds, and a field the line did not have is inserted where the schema declares it\n return tableFields\n ? mergeFields(base, row, { fields: tableFields, keyOrder: this.keyOrders.get(tableName) })\n : row;\n });\n\n return [...writtenRows, ...newRows];\n }\n\n /**\n * Pair each row with the JSONL line it came from, indexed the same way as `rows`.\n * Returns undefined when the rows cannot be matched and the caller can do without it.\n */\n private matchExistingRows(\n tableName: string,\n rows: JsonObject[],\n existingRows: JsonObject[],\n options: { required: boolean },\n ): Array<JsonObject | undefined> | undefined {\n // Nothing in the file to preserve, so every row is one the file never had\n if (existingRows.length === 0) {\n return rows.map(() => undefined);\n }\n\n const pkName = this.schemas.get(tableName)?.columns.find((col) => col.primaryKey)?.name;\n const pkValues = pkName ? existingRows.map((row) => row[pkName]) : [];\n const hasUsablePk =\n pkName !== undefined &&\n pkValues.every((value) => value !== undefined && value !== null) &&\n new Set(pkValues.map((value) => String(value))).size === pkValues.length;\n\n if (hasUsablePk) {\n const byPk = new Map(existingRows.map((row, index) => [String(pkValues[index]), row]));\n return rows.map((row) => {\n const pkValue = row[pkName!];\n return pkValue === undefined || pkValue === null ? undefined : byPk.get(String(pkValue));\n });\n }\n\n // No usable primary key in the file: fall back to matching rows to lines by position.\n // Only safe while the row count is unchanged, since anything else means rows were\n // added or removed and positions no longer line up.\n if (rows.length !== existingRows.length) {\n if (!options.required) {\n return undefined;\n }\n throw new Error(\n `Cannot write back selected fields for table '${tableName}': ` +\n `the file has ${existingRows.length} row(s) but the table has ${rows.length}, and ` +\n `${pkName ? `column '${pkName}' is not usable as a primary key in the file` : 'the table has no primary key'}, ` +\n `so rows cannot be matched to their existing lines.`,\n );\n }\n\n return existingRows;\n }\n\n /**\n * Read the rows a JSONL file currently holds, treating a missing file as empty, and refuse to go on\n * when the file is not the one this database last read or wrote: writing over it would drop the\n * changes made to it since\n */\n private async readUnchangedRows(jsonlPath: string): Promise<JsonObject[]> {\n const result = await JsonlReader.readSnapshot(jsonlPath);\n if (!result.ok && (result.error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw result.error;\n }\n const snapshot = result.ok ? result.value : { rows: ok<JsonObject[]>([]), contentHash: undefined };\n\n const knownHash = this.fileHashes.get(jsonlPath);\n if (\n (knownHash !== undefined && snapshot.contentHash !== knownHash) ||\n (this.config.writeDataSets && !this.scannedJsonlFiles.includes(jsonlPath) && snapshot.contentHash !== undefined)\n ) {\n const conflictError = new Error(\n `JSONL file '${jsonlPath}' was changed after the database read it, so it was not overwritten. ` +\n `Create the database again and call initialize() to load the current file, then retry the write.`,\n ) as JsonlConflictError;\n conflictError.name = 'JsonlConflictError';\n conflictError.file = jsonlPath;\n throw conflictError;\n }\n\n return unwrap(snapshot.rows);\n }\n\n /**\n * Tell whether the files the tables were loaded from changed since this database last read or\n * wrote them: a JSONL file was edited, added or removed, or a table's schema file was edited, added\n * or removed. When they did, the database holds rows or a schema the files no longer have; create it\n * again and call initialize() to load the current files.\n */\n async hasExternalChanges(): Promise<Result<boolean, Error>> {\n try {\n return ok((await this.findExternalChangesInternal()).length > 0);\n } catch (error) {\n return err(toError(error));\n }\n }\n\n /**\n * The files that changed since this database last read or wrote them, as {@link hasExternalChanges}\n * tells: each JSONL file edited, added or removed, and each schema file edited, added or removed\n */\n async findExternalChanges(): Promise<Result<string[], Error>> {\n try {\n return ok(await this.findExternalChangesInternal());\n } catch (error) {\n return err(toError(error));\n }\n }\n\n private async findExternalChangesInternal(): Promise<string[]> {\n // A write-back still in flight has written its file before it records the file's hash\n await this.waitForPendingSyncs();\n const changed = new Set<string>();\n\n for (const [file, knownHash] of this.observedHashes) {\n const content = await readFile(file, 'utf-8').catch((error: NodeJS.ErrnoException) => {\n if (error.code === 'ENOENT') return undefined;\n throw error;\n });\n if (content === undefined || hashJsonlContent(content) !== knownHash) changed.add(file);\n }\n\n const tables = await DirectoryScanner.scanDirectory(this.config.dataDir);\n const scanned = new Set(listJsonlFiles(tables));\n for (const file of this.scannedJsonlFiles) if (!scanned.has(file)) changed.add(file);\n for (const file of scanned) if (!this.scannedJsonlFiles.includes(file)) changed.add(file);\n\n for (const name of new Set([...this.schemaFileStates.keys(), ...tables.keys()])) {\n const knownState = this.schemaFileStates.get(name) ?? '';\n const config = tables.get(name);\n const state = config ? await this.schemaFileState(name, config) : await this.stateOfKnownSchemaFile(knownState);\n if (state !== knownState) changed.add((state || knownState).split('\\0')[0]);\n }\n return [...changed];\n }\n\n /** The state of the schema file a state names, for a table whose JSONL file is gone */\n private async stateOfKnownSchemaFile(knownState: string): Promise<string> {\n if (!knownState) return '';\n const schemaPath = knownState.split('\\0')[0];\n const content = await readFile(schemaPath, 'utf-8').catch((error: NodeJS.ErrnoException) => {\n if (error.code === 'ENOENT') return undefined;\n throw error;\n });\n return content === undefined ? '' : `${schemaPath}\\0${hashJsonlContent(content)}`;\n }\n\n private async schemaFileState(tableName: string, config: TableConfig): Promise<string> {\n if (config.validationSchema) return '';\n const schemaPath = await this.findTableSchemaFile(tableName, config);\n if (!schemaPath) return '';\n return `${schemaPath}\\0${hashJsonlContent(await readFile(schemaPath, 'utf-8'))}`;\n }\n\n /**\n * Sync database changes back to JSONL files\n * Uses backward transformation when available\n * @param tableName Optional table name to sync. If not provided, syncs all loaded tables\n * @param options Optional sync options, e.g. the fields to write back\n */\n async sync(tableName?: string, options?: SyncOptions): Promise<Result<void, Error>> {\n try {\n await this.syncInternal(tableName, options);\n return ok(undefined);\n } catch (error) {\n return err(toError(error));\n }\n }\n\n private async syncInternal(tableName?: string, options?: SyncOptions): Promise<void> {\n this.refuseWhileTransactionSettles('sync');\n this.assertWritable(tableName);\n if (this.inTransaction) {\n throw new Error(\n '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',\n );\n }\n\n if (tableName) {\n // Sync only the specified table\n if (!this.schemas.has(tableName)) {\n throw new Error(`Table '${tableName}' is not loaded`);\n }\n // The caller named both the table and the fields, so a field it does not have is a mistake\n await this.syncTable(tableName, { ...options, strictFields: options?.fields !== undefined });\n } else {\n // Sync all tables that are loaded (present in schemas map)\n for (const [name] of this.schemas) {\n await this.syncTable(name, options);\n }\n }\n }\n\n /**\n * Execute a function within a transaction\n * Automatically commits on success or rolls back on error.\n *\n * Note: `tx` (the argument `fn` receives) is the same Result-returning API as `this` - a failed\n * `tx.insert()`/`tx.update()`/etc. inside `fn` does not throw and therefore does not roll back the\n * transaction on its own. To abort on such a failure, check the Result and `throw result.error`\n * (or any error) from `fn`; only a thrown error rolls the transaction back.\n */\n async transaction<T>(fn: (tx: LinesDB<Tables>) => Promise<T> | T): Promise<Result<T, Error>> {\n if (this.inTransaction || this.transactionStarting) {\n return err(new Error('Nested transactions are not supported'));\n }\n // Not left to inTransaction: it is set only after the awaits below, which a second call could slip past\n this.transactionStarting = true;\n const token = {};\n\n let fieldChangesBefore: Map<string, Map<string, FieldChanges>> | undefined;\n let rawSqlTablesBefore: Set<string> | undefined;\n let linesWithUnknownFieldsBefore: Map<string, Map<string, JsonObject>> | undefined;\n let originsBefore: Map<string, Map<string, RowOrigin>> | undefined;\n let columnsBefore: Map<string, TableSchema['columns']> | undefined;\n const scannedBefore = [...this.scannedJsonlFiles];\n let written: PreparedWriteBack[] = [];\n try {\n // Not beginning first: a pending auto-sync would then read, and write out, rows still uncommitted\n await this.waitForPendingSyncs();\n originsBefore = new Map([...this.rowOriginsByRowid].map(([name, origins]) => [name, new Map(origins)]));\n // The columns added to a table made from given columns go with the transaction that added them\n columnsBefore = new Map(\n [...this.tablesFromGivenColumns].map((name) => [name, [...(this.schemas.get(name)?.columns ?? [])]]),\n );\n fieldChangesBefore = cloneFieldChanges(this.fieldChanges);\n rawSqlTablesBefore = new Set(this.rawSqlTables);\n linesWithUnknownFieldsBefore = new Map(\n Array.from(this.linesWithUnknownFields, ([tableName, lines]) => [tableName, new Map(lines)]),\n );\n this.db.exec('BEGIN TRANSACTION');\n this.settleUndos = [];\n this.inTransaction = true;\n this.transactionToken = token;\n this.transactionStarting = false;\n this.transactionChanges = new Set();\n\n let result: T;\n try {\n result = await fn(this.scopedToTransaction(token));\n } finally {\n // Not open to writes from here, whether the callback returned or threw: the rows are read for the\n // write-back and the files put back, and a write made during those awaits would join the\n // transaction without reaching the files, or be rolled back after it reported success\n this.transactionClosing = true;\n }\n\n // Written back before COMMIT, so a failed write-back rolls the change back instead of leaving the\n // database holding rows its files do not; a read-only database has no changes to write back\n if (!this.isReadOnlyDataSet()) {\n written = await this.writeBackTogether(this.tablesChangedInTransaction());\n }\n\n this.db.exec('COMMIT');\n this.settleUndos = undefined;\n this.inTransaction = false;\n this.transactionChanges = undefined;\n\n return ok(result);\n } catch (error) {\n this.transactionStarting = false;\n this.transactionChanges = undefined;\n if (originsBefore) this.rowOriginsByRowid = originsBefore;\n for (const [name, columns] of columnsBefore ?? []) {\n const schema = this.schemas.get(name);\n if (schema) schema.columns = columns;\n }\n this.scannedJsonlFiles = scannedBefore;\n if (fieldChangesBefore) this.fieldChanges = fieldChangesBefore;\n if (rawSqlTablesBefore) this.rawSqlTables = rawSqlTablesBefore;\n if (linesWithUnknownFieldsBefore) this.linesWithUnknownFields = linesWithUnknownFieldsBefore;\n // Not only when writing a file fails: a COMMIT failing after the writes leaves files holding rolled-back rows\n const failure = await this.restoreAll(written, error);\n if (this.inTransaction) {\n try {\n this.db.exec('ROLLBACK');\n } catch (_rollbackError) {\n // Report the original error rather than a failure to roll back\n }\n }\n // Not before the ROLLBACK: a read on the connection while the files are put back still sees the\n // rolled-back row, and would read it with the column type it had before the write\n for (const undo of [...(this.settleUndos ?? [])].reverse()) undo();\n this.settleUndos = undefined;\n this.inTransaction = false;\n return err(toError(failure));\n } finally {\n this.transactionClosing = false;\n this.transactionToken = undefined;\n }\n }\n\n /**\n * The object a transaction() callback receives. Calls on it are marked as the transaction's own for as\n * long as they run; a write made through the database itself in the meantime is refused, since writes are\n * synchronous and cannot be queued until the transaction ends\n */\n private scopedToTransaction(token: object): LinesDB<Tables> {\n return new Proxy(this, {\n get: (target, property) => {\n const value: unknown = Reflect.get(target, property, target);\n if (typeof value !== 'function') return value;\n return (...args: unknown[]) => {\n const before = target.viaTransactionObject;\n target.viaTransactionObject = before || target.transactionToken === token;\n try {\n return value.apply(target, args);\n } finally {\n target.viaTransactionObject = before;\n }\n };\n },\n });\n }\n\n /**\n * Wait for every queued sync to finish, so a fire-and-forget auto-sync is not dropped\n */\n private async waitForPendingSyncs(): Promise<void> {\n const awaited = new Set<Promise<void>>();\n // Queued promises never reject: syncTable stores them with their rejection swallowed\n let pending = Array.from(this.syncQueue.values());\n\n while (pending.length > 0) {\n for (const promise of pending) {\n awaited.add(promise);\n }\n await Promise.all(pending);\n pending = Array.from(this.syncQueue.values()).filter((promise) => !awaited.has(promise));\n }\n }\n\n /**\n * Close the database connection\n */\n async close(): Promise<Result<void, Error>> {\n try {\n await this.waitForPendingSyncs();\n try {\n this.db.close();\n } catch (_error) {\n // Ignore errors if database is already closed\n }\n return ok(undefined);\n } catch (error) {\n return err(toError(error));\n }\n }\n\n /**\n * Get a handle for running SQL on the underlying SQLite database. It wraps the connection rather than\n * being it, also outside a transaction: while a transaction() callback runs, SQL that changes rows is\n * refused unless the handle came from the callback's `tx`, and SQL that would end the transaction is\n * refused for every handle. Outside a transaction it runs SQL unchanged.\n */\n getDb(): SQLiteDatabase {\n // Handed out as a wrapper even outside a transaction: a handle kept from before one would otherwise\n // write while its callback awaits, unseen by the write-back, and be committed or rolled back with it\n const token = this.viaTransactionObject ? this.transactionToken : undefined;\n // Not captured as a boolean: a handle kept from an earlier transaction must not count as the running one's\n const viaTransaction = () => token !== undefined && token === this.transactionToken;\n const idle = () => !this.inTransaction && !this.transactionStarting && !this.transactionClosing;\n // Checked each time SQL runs, not when the handle is taken: SQL that would end a transaction must be\n // refused, and one that changes rows tracked, whichever transaction is open by then\n const guarded = <T>(sql: string, run: () => T): T => {\n if (idle() && !this.hasSeveralDataDirs()) return run();\n this.refuseUnsafeSql(sql, viaTransaction());\n return this.readOnlyWhileTransactionSettles(() => this.trackRawSql(run), viaTransaction());\n };\n return {\n prepare: (sql: string) => {\n // Also when prepared: SQLite runs some pragmas then, not only when the statement is stepped\n if (!idle() || this.hasSeveralDataDirs()) this.refuseUnsafeSql(sql, viaTransaction());\n const statement = this.readOnlyWhileTransactionSettles(() => this.db.prepare(sql), viaTransaction());\n return {\n run: (...params: unknown[]) => guarded(sql, () => statement.run(...params)),\n get: (...params: unknown[]) => guarded(sql, () => statement.get(...params)),\n all: (...params: unknown[]) => guarded(sql, () => statement.all(...params)),\n };\n },\n exec: (sql: string) => guarded(sql, () => this.db.exec(sql)),\n close: () => this.db.close(),\n };\n }\n}\n\nfunction listJsonlFiles(tables: Map<string, TableConfig>): string[] {\n return Array.from(tables.values())\n .flatMap((config) => config.jsonlPaths ?? [config.jsonlPath])\n .sort();\n}\n","import { randomBytes } from 'node:crypto';\nimport { chmod, readdir, readFile, realpath, rename, rm, stat, writeFile } from 'node:fs/promises';\nimport { basename, dirname, join } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { type Result, ok, err, toError } from './result.js';\nimport { hasBackward, type BiDirectionalSchema } from './schema.js';\nimport { findSchemaFile } from './schema-extensions.js';\nimport type { JsonlConflictError, JsonObject, JsonValue, StandardSchema, Table } from './types.js';\n\n/** Computes the values a row gets, from the row as its line holds it */\nexport type RowFiller = (row: JsonObject) => Record<string, unknown>;\n\nexport interface FillFieldsOptions {\n /** One or more data directories or `.jsonl` files */\n path: string | readonly string[];\n /** Fields to fill. Defaults to each table's primary key: `primaryKey` in its schema file, or `id` */\n fields?: readonly string[];\n /** Directory the `<Table>.schema.{ts,mts,cts}` files are looked up in. Defaults to each file's data directory */\n schemaDir?: string;\n /**\n * Builds the function that computes a table's row values from its schema module. Defaults to the\n * value its validation schema (the `schema` or default export) gives a row, after its backward\n * transformation; a row the schema rejects gains nothing. Throwing stops the fill before any file\n * is written.\n */\n loadFiller?: (schemaModule: Record<string, unknown>, context: { tableName: string; schemaPath: string }) => RowFiller;\n}\n\nexport interface FilledFile {\n /** Name of the table, matching the JSONL file name */\n table: string;\n file: string;\n /** The fields written into at least one of its rows */\n fields: string[];\n /** How many rows gained a value */\n count: number;\n}\n\nexport interface FillFieldsResult {\n filled: FilledFile[];\n /** Tables without a schema file, so nothing could compute their values */\n tablesWithoutSchema: string[];\n /** The 1-based lines of each file that are not JSON objects, so nothing was filled in there */\n unreadableLines: Array<{ file: string; lines: number[] }>;\n /** Fields to fill that no row of any table got a value for */\n unproducedFields: string[];\n}\n\n/** A JSONL line, kept as text so a line that gains nothing is written back verbatim */\ninterface Line {\n text: string;\n /** The separator after the line, kept so CRLF survives */\n eol: string;\n row: JsonObject | undefined;\n}\n\n/**\n * Fill the named fields into the rows of the JSONL files that have no value for them, with the values\n * each table computes for a row. A value already in the file is never replaced, and a line that gains\n * nothing is left byte for byte; a line that does gain a value is written with its keys in the order\n * the computed row lists them. Every value is computed before any file is written.\n */\nexport async function fillFields(options: FillFieldsOptions): Promise<Result<FillFieldsResult, Error>> {\n try {\n return ok(await fillFieldsInternal(options));\n } catch (error) {\n return err(toError(error));\n }\n}\n\nasync function fillFieldsInternal(options: FillFieldsOptions): Promise<FillFieldsResult> {\n if (options.fields && options.fields.length === 0) {\n throw new Error('No fields to fill. Name at least one field.');\n }\n const paths = typeof options.path === 'string' ? [options.path] : options.path;\n if (paths.length === 0) throw new Error('No paths to fill. Name at least one path.');\n const sources = new Map<string, { table: string; file: string; target: string; schemaDir: string }>();\n for (const path of paths) {\n const { dataDir, tableNames } = await resolveTables(path);\n for (const table of tableNames) {\n const file = join(dataDir, `${table}.jsonl`);\n const key = await realpath(file);\n if (!sources.has(key)) sources.set(key, { table, file, target: key, schemaDir: options.schemaDir ?? dataDir });\n }\n }\n const loadFiller = options.loadFiller ?? fillerFromValidationSchema;\n\n const tablesWithoutSchema: string[] = [];\n const tables: Array<{ table: string; file: string; target: string; fields: readonly string[]; fill: RowFiller }> = [];\n for (const { table, file, target, schemaDir } of sources.values()) {\n const schemaPath = await findSchemaFile(schemaDir, table);\n if (!schemaPath) {\n if (!tablesWithoutSchema.includes(table)) tablesWithoutSchema.push(table);\n continue;\n }\n const schemaModule = (await import(`${pathToFileURL(schemaPath).href}?t=${Date.now()}`)) as Record<string, unknown>;\n tables.push({\n table,\n file,\n target,\n fields: options.fields ?? [primaryKeyOf(schemaModule)],\n fill: loadFiller(schemaModule, { tableName: table, schemaPath }),\n });\n }\n\n const produced = new Set<string>();\n const unreadableLines: FillFieldsResult['unreadableLines'] = [];\n const filled: FilledFile[] = [];\n const writes: Array<{ file: string; target: string; read: string; content: string }> = [];\n for (const { table, file, target, fields, fill } of tables) {\n const read = await readFile(target, 'utf-8');\n const bom = read.startsWith('\\u{feff}') ? '\\u{feff}' : '';\n const lines = splitLines(read.slice(bom.length));\n const written = new Set<string>();\n const unreadable: number[] = [];\n let count = 0;\n\n lines.forEach((line, index) => {\n if (!line.row) {\n if (line.text.trim() !== '') unreadable.push(index + 1);\n return;\n }\n const computed = fill(structuredClone(line.row));\n const gained = fields.filter((field) => {\n if (isBlank(ownValue(computed, field))) return false;\n produced.add(field);\n // Not judged by isBlank: a value the line holds, even {}, is one the file already has\n return ownValue(line.row!, field) === undefined || ownValue(line.row!, field) === null;\n });\n if (gained.length === 0) return;\n for (const field of gained) {\n setField(line.row, field, computed[field] as JsonValue);\n written.add(field);\n }\n line.text = serializeRow(line.row, Object.keys(computed));\n count += 1;\n });\n\n if (unreadable.length > 0) unreadableLines.push({ file, lines: unreadable });\n if (count === 0) continue;\n writes.push({ file, target, read, content: bom + lines.map((line) => `${line.text}${line.eol}`).join('') });\n filled.push({ table, file, fields: [...written], count });\n }\n\n // Not checking each file as it is written: a change found in a later file would leave the earlier\n // ones already filled\n for (const { file, target, read } of writes) {\n if ((await readFile(target, 'utf-8')) !== read) {\n const error = new Error(\n `JSONL file '${file}' was changed after it was read, so no file was filled. Run the fill again.`,\n ) as JsonlConflictError;\n error.name = 'JsonlConflictError';\n error.file = file;\n throw error;\n }\n }\n await replaceAll(writes);\n\n const named = options.fields ?? [...new Set(tables.flatMap(({ fields }) => fields))];\n return {\n filled,\n tablesWithoutSchema,\n unreadableLines,\n unproducedFields: sources.size > 0 ? named.filter((field) => !produced.has(field)) : [],\n };\n}\n\n/**\n * Write every file or none: each content goes to a temporary file first, the temporaries replace the\n * files once all are written, and the files already replaced are put back when a later one fails\n */\nasync function replaceAll(\n writes: Array<{ file: string; target: string; read: string; content: string }>,\n): Promise<void> {\n const staged = writes.map((write) => ({\n ...write,\n temporary: `${write.target}.${randomBytes(6).toString('hex')}.tmp`,\n }));\n const replaced: typeof staged = [];\n try {\n for (const { target, temporary, content } of staged) {\n await writeFile(temporary, content, 'utf-8');\n // Not left to the umask: the file replaced would otherwise lose a mode such as 0600\n await chmod(temporary, (await stat(target)).mode & 0o7777);\n }\n for (const write of staged) {\n await rename(write.temporary, write.target);\n replaced.push(write);\n }\n } catch (error) {\n const notRestored: string[] = [];\n for (const { file, target, read } of replaced) {\n await writeFile(target, read, 'utf-8').catch(() => notRestored.push(file));\n }\n await Promise.all(staged.map(({ temporary }) => rm(temporary, { force: true })));\n if (notRestored.length === 0) throw error;\n throw new Error(\n `${toError(error).message}\\nThese files could not be put back and stay filled: ${notRestored.join(', ')}`,\n { cause: error },\n );\n }\n}\n\nasync function resolveTables(path: string): Promise<{ dataDir: string; tableNames: string[] }> {\n const stats = await stat(path);\n if (stats.isDirectory()) {\n const entries = await readdir(path);\n const tableNames = entries\n .filter((entry) => entry.endsWith('.jsonl'))\n .map((entry) => basename(entry, '.jsonl'))\n .sort();\n return { dataDir: path, tableNames };\n }\n if (stats.isFile() && path.endsWith('.jsonl')) {\n return { dataDir: dirname(path), tableNames: [basename(path, '.jsonl')] };\n }\n throw new Error(`Invalid path: ${path}. Must be a directory or .jsonl file.`);\n}\n\nfunction primaryKeyOf(schemaModule: Record<string, unknown>): string {\n const schema = (schemaModule.schema ?? schemaModule.default) as { primaryKey?: unknown } | undefined;\n const primaryKey = schema?.primaryKey ?? schemaModule.primaryKey;\n return typeof primaryKey === 'string' ? primaryKey : 'id';\n}\n\nfunction fillerFromValidationSchema(\n schemaModule: Record<string, unknown>,\n { schemaPath }: { schemaPath: string },\n): RowFiller {\n const schema = (schemaModule.schema ?? schemaModule.default) as StandardSchema | undefined;\n if (!schema || typeof schema !== 'object' || !('~standard' in schema)) {\n throw new Error(`${schemaPath} does not export a StandardSchema as \\`schema\\` or as its default export`);\n }\n return (row) => {\n const result = schema['~standard'].validate(row);\n if (result instanceof Promise) {\n throw new Error(`${schemaPath}: asynchronous validation is not supported`);\n }\n if (result.issues) return {};\n return hasBackward(schema)\n ? ((schema as BiDirectionalSchema<Table, Table>).backward!(result.value) as Record<string, unknown>)\n : result.value;\n };\n}\n\nfunction ownValue(row: Record<string, unknown>, field: string): unknown {\n return Object.hasOwn(row, field) ? row[field] : undefined;\n}\n\n// Not `row[field] = value`: a field named `__proto__` would go through the inherited setter and leave\n// no own property for the serializer to read back\nfunction setField(row: JsonObject, field: string, value: JsonValue): void {\n Object.defineProperty(row, field, { value, enumerable: true, writable: true, configurable: true });\n}\n\nfunction isBlank(value: unknown): boolean {\n if (value === undefined || value === null) return true;\n if (typeof value !== 'object' || Array.isArray(value)) return false;\n // A nested field the row never had can come back as an object of blank values, which fills nothing in\n return Object.values(value).every(isBlank);\n}\n\nfunction splitLines(content: string): Line[] {\n if (content === '') return [];\n return content.split('\\n').map((raw, index, all) => {\n const carriage = raw.endsWith('\\r') ? '\\r' : '';\n const text = carriage ? raw.slice(0, -1) : raw;\n let row: JsonObject | undefined;\n if (text.trim() !== '') {\n try {\n const parsed: unknown = JSON.parse(text);\n row =\n parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? (parsed as JsonObject) : undefined;\n } catch {\n row = undefined;\n }\n }\n return { text, eol: index === all.length - 1 ? carriage : `${carriage}\\n`, row };\n });\n}\n\n/** The row with its keys in the order the computed row lists them, and keys it does not list after those */\nfunction serializeRow(row: JsonObject, fieldOrder: string[]): string {\n const rank = new Map(fieldOrder.map((field, index) => [field, index]));\n const rankOf = (key: string): number => rank.get(key) ?? fieldOrder.length;\n const ordered = Object.entries(row).sort(([a], [b]) => rankOf(a) - rankOf(b));\n const out: JsonObject = {};\n for (const [key, value] of ordered) setField(out, key, value);\n return JSON.stringify(out);\n}\n","import { readdir } from 'node:fs/promises';\nimport { join, relative, basename, dirname, isAbsolute } from 'node:path';\nimport { writeFile, mkdir } from 'node:fs/promises';\nimport { findSchemaFileInEntries, rewriteExtensionForImport } from './schema-extensions.js';\n\nexport interface TypeGeneratorOptions {\n dataDir: string;\n projectRoot?: string; // Default: current working directory\n output?: string; // Output file path (default: db.ts in dataDir)\n}\n\ninterface TableInfo {\n tableName: string;\n schemaFile?: string;\n}\n\nexport class TypeGenerator {\n private dataDir: string;\n private projectRoot: string;\n private outputFile: string;\n private dataDirPath: string;\n\n constructor(options: TypeGeneratorOptions) {\n // For testing: allow overriding projectRoot via environment variable\n const envProjectRoot = process.env.LINES_DB_TEST_PROJECT_ROOT;\n this.projectRoot = envProjectRoot !== undefined ? envProjectRoot : options.projectRoot || process.cwd();\n this.dataDir = options.dataDir;\n this.dataDirPath = isAbsolute(this.dataDir) ? this.dataDir : join(this.projectRoot, this.dataDir);\n this.outputFile = options.output\n ? isAbsolute(options.output)\n ? options.output\n : join(this.projectRoot, options.output)\n : join(this.dataDirPath, 'db.ts');\n }\n\n /**\n * Generate types file from JSONL files and their optional schema files.\n */\n async generate(): Promise<string> {\n // Find all JSONL files and their corresponding schema files\n const tables = await this.findTables();\n\n if (tables.length === 0) {\n throw new Error(`No JSONL files found in ${this.dataDirPath}. Place one or more *.jsonl files in the directory.`);\n }\n\n // Generate type declarations\n const content = this.generateTypeDeclarations(tables);\n\n // Ensure output directory exists\n const outputDir = dirname(this.outputFile);\n await mkdir(outputDir, { recursive: true });\n\n // Write to file\n await writeFile(this.outputFile, content, 'utf-8');\n console.log(`Generated types at ${this.outputFile}`);\n return this.outputFile;\n }\n\n /**\n * Find all *.jsonl files and check if they have corresponding *.schema.ts files\n */\n private async findTables(): Promise<TableInfo[]> {\n try {\n const entries = await readdir(this.dataDirPath, { withFileTypes: true });\n const tables: TableInfo[] = [];\n\n for (const entry of entries) {\n if (entry.isFile() && entry.name.endsWith('.jsonl')) {\n const tableName = basename(entry.name, '.jsonl');\n const schemaFilePath = findSchemaFileInEntries(this.dataDirPath, tableName, entries);\n\n tables.push({\n tableName,\n schemaFile: schemaFilePath,\n });\n }\n }\n\n return tables;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new Error(`Data directory not found: ${this.dataDirPath}. Set lines-db.dataDir to the correct location.`);\n }\n throw error;\n }\n }\n\n /**\n * Generate type declaration content\n */\n private generateTypeDeclarations(tables: TableInfo[]): string {\n const imports: string[] = [];\n const tableEntries: string[] = [];\n const usedAliases = new Set<string>();\n\n for (const table of tables) {\n const tableKey = this.formatTableKey(table.tableName);\n\n if (table.schemaFile) {\n // Table has a schema file\n const schemaIdentifier = this.createSchemaIdentifier(table.tableName, usedAliases);\n usedAliases.add(schemaIdentifier);\n\n // Calculate relative path from output file to schema file\n let relativePath = rewriteExtensionForImport(\n relative(join(this.outputFile, '..'), table.schemaFile).replace(/\\\\/g, '/'), // Convert Windows paths to Unix-style\n );\n\n // Ensure relative path starts with './' or '../'\n if (!relativePath.startsWith('.')) {\n relativePath = './' + relativePath;\n }\n\n // Add import statement for schema\n imports.push(`import { schema as ${schemaIdentifier} } from '${relativePath}';`);\n\n // Add table entry with InferOutput\n tableEntries.push(` ${tableKey}: InferOutput<typeof ${schemaIdentifier}>;`);\n } else {\n // Table has no schema file, use Record<string, unknown>\n tableEntries.push(` ${tableKey}: Record<string, unknown>;`);\n }\n }\n\n // Generate full content\n const importSection = imports.length > 0 ? `${imports.join('\\n')}\\n` : '';\n const inferOutputImport = imports.length > 0 ? ', InferOutput' : '';\n\n return `// Auto-generated by lines-db\n// Do not edit this file manually\n\n${importSection}import type { DatabaseConfig${inferOutputImport} } from 'lines-db';\nimport { fileURLToPath } from 'node:url';\nimport { dirname } from 'node:path';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\nexport type Tables = {\n${tableEntries.join('\\n')}\n};\n\nexport const config: DatabaseConfig<Tables> = {\n dataDir: __dirname,\n};\n`;\n }\n\n private createSchemaIdentifier(tableName: string, usedAliases: Set<string>): string {\n const camel = toCamelCase(tableName);\n const sanitizedBase = sanitizeIdentifier(camel);\n let base = sanitizedBase || 'table';\n\n if (!/^[A-Za-z_$]/.test(base)) {\n base = `_${base}`;\n }\n\n let candidate = `${base}Schema`;\n let suffix = 1;\n while (usedAliases.has(candidate)) {\n candidate = `${base}${++suffix}Schema`;\n }\n\n return candidate;\n }\n\n private formatTableKey(tableName: string): string {\n const identifierPattern = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n if (identifierPattern.test(tableName)) {\n return tableName;\n }\n const escaped = tableName.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\");\n return `'${escaped}'`;\n }\n}\n\nfunction toCamelCase(value: string): string {\n const parts = value\n .split(/[^A-Za-z0-9]+/)\n .filter(Boolean)\n .map((part) => part.toLowerCase());\n\n if (parts.length === 0) {\n return value;\n }\n\n const [first, ...rest] = parts;\n return first + rest.map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join('');\n}\n\nfunction sanitizeIdentifier(value: string): string {\n return value.replace(/[^A-Za-z0-9_$]/g, '');\n}\n","import { join } from 'node:path';\nimport type { JsonObject } from './types.js';\nimport { JsonlReader } from './jsonl-reader.js';\nimport { LinesDB } from './database.js';\nimport { unwrap } from './result.js';\n\nexport interface TableValidationOptions {\n dataDir: string;\n tableName: string;\n rows: JsonObject[];\n}\n\n/**\n * Validate a table by temporarily supplying in-memory rows while reusing the existing LinesDB validation pipeline.\n * If validation fails, throws an error with validation details.\n */\nexport async function ensureTableRowsValid(options: TableValidationOptions): Promise<void> {\n const tablePath = join(options.dataDir, `${options.tableName}.jsonl`);\n const overrides = new Map<string, JsonObject[]>([[tablePath, options.rows]]);\n\n await JsonlReader.withOverrides(overrides, async () => {\n const db = LinesDB.create({ dataDir: options.dataDir });\n try {\n // Initialize only the target table\n const result = unwrap(await db.initialize({ tableName: options.tableName }));\n\n // If validation failed, throw an error with details\n if (!result.valid) {\n const errorCount = result.errors.length;\n const errorDetails = result.errors\n .map((e) => {\n const issueMessages = e.issues.map((issue) => issue.message).join(', ');\n return ` Row ${e.rowIndex}: ${issueMessages}`;\n })\n .join('\\n');\n\n throw new Error(\n `Validation failed for table '${options.tableName}' (${errorCount} error(s)):\\n${errorDetails}`,\n );\n }\n } finally {\n await db.close();\n }\n });\n}\n","import type { StandardSchemaIssue } from './types.js';\nimport { styleText } from 'node:util';\n\nexport interface ValidationErrorInfo {\n file: string;\n rowIndex: number;\n issues: ReadonlyArray<StandardSchemaIssue>;\n data?: unknown;\n originalData?: unknown;\n}\n\nexport interface ForeignKeyErrorInfo {\n file: string;\n rowIndex: number;\n column: string;\n value: unknown;\n referencedTable: string;\n referencedColumn: string;\n data?: unknown;\n}\n\nexport interface ErrorFormatterOptions {\n verbose?: boolean;\n}\n\nexport class ErrorFormatter {\n private verbose: boolean;\n\n constructor(options: ErrorFormatterOptions = {}) {\n this.verbose = options.verbose ?? false;\n }\n\n /**\n * Format validation errors\n */\n formatValidationErrors(errors: ValidationErrorInfo[]): string {\n if (this.verbose) {\n return this.formatValidationErrorsVerbose(errors);\n }\n return this.formatValidationErrorsCompact(errors);\n }\n\n /**\n * Format foreign key error\n */\n formatForeignKeyError(error: ForeignKeyErrorInfo): string {\n if (this.verbose) {\n return this.formatForeignKeyErrorVerbose(error);\n }\n return this.formatForeignKeyErrorCompact(error);\n }\n\n /**\n * Format compact (default) validation errors\n */\n private formatValidationErrorsCompact(errors: ValidationErrorInfo[]): string {\n const lines: string[] = [];\n\n for (const error of errors) {\n for (const issue of error.issues) {\n const fieldPath = this.getFieldPath(issue);\n const line = `${error.file}:${error.rowIndex + 1} • ${fieldPath}: ${issue.message}`;\n lines.push(line);\n }\n }\n\n return lines.join('\\n');\n }\n\n /**\n * Format verbose validation errors\n */\n private formatValidationErrorsVerbose(errors: ValidationErrorInfo[]): string {\n const blocks: string[] = [];\n\n for (let i = 0; i < errors.length; i++) {\n const error = errors[i];\n const isLast = i === errors.length - 1;\n const prefix = isLast ? '└─' : '├─';\n const linePrefix = isLast ? ' ' : '│ ';\n\n const lines: string[] = [`${prefix} ${error.file}:${error.rowIndex + 1}`];\n\n for (const issue of error.issues) {\n const fieldPath = this.getFieldPath(issue);\n lines.push(`${linePrefix}Field: ${fieldPath}`);\n lines.push(`${linePrefix}Error: ${issue.message}`);\n }\n\n // Show original data if available (migrate case)\n if (error.originalData !== undefined) {\n lines.push(`${linePrefix}Original data: ${JSON.stringify(error.originalData)}`);\n }\n\n // Show data\n if (error.data !== undefined) {\n const label = error.originalData !== undefined ? 'Transformed data' : 'Data';\n lines.push(`${linePrefix}${label}: ${JSON.stringify(error.data)}`);\n }\n\n blocks.push(lines.join('\\n'));\n }\n\n return blocks.join('\\n│\\n');\n }\n\n /**\n * Format compact foreign key error\n */\n private formatForeignKeyErrorCompact(error: ForeignKeyErrorInfo): string {\n 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})`;\n }\n\n /**\n * Format verbose foreign key error\n */\n private formatForeignKeyErrorVerbose(error: ForeignKeyErrorInfo): string {\n const lines: string[] = [\n `└─ ${error.file}:${error.rowIndex + 1}`,\n ` Type: Foreign Key Violation`,\n ` Field: ${error.column}`,\n ` Value: ${JSON.stringify(error.value)}`,\n ` References: ${error.referencedTable}(${error.referencedColumn})`,\n ` Error: Referenced value does not exist in target table`,\n ];\n\n if (error.data !== undefined) {\n lines.push(` Data: ${JSON.stringify(error.data)}`);\n }\n\n return lines.join('\\n');\n }\n\n /**\n * Get field path from issue\n */\n private getFieldPath(issue: StandardSchemaIssue): string {\n if (!issue.path || issue.path.length === 0) {\n return 'root';\n }\n\n return issue.path\n .map((segment) => {\n if (typeof segment === 'object' && segment !== null && 'key' in segment) {\n return String(segment.key);\n }\n return String(segment);\n })\n .join('.');\n }\n\n /**\n * Format error header with count\n */\n formatErrorHeader(count: number, file?: string): string {\n const fileInfo = file ? ` in ${file}` : '';\n return styleText('red', `✗ Found ${count} error(s)${fileInfo}`);\n }\n\n /**\n * Format migration failure header\n */\n formatMigrationFailureHeader(): string {\n return styleText('red', '\\n✗ Migration failed and was rolled back');\n }\n}\n","import { readFile, realpath, stat } from 'node:fs/promises';\nimport { basename, dirname, resolve } from 'node:path';\nimport { z } from 'zod';\nimport type { DatabaseConfig } from './types.js';\n\nconst directories = z.array(z.string().min(1)).min(1);\nconst datasetConfigSchema = z.strictObject({\n schemaDir: z.string().min(1),\n base: directories,\n datasets: z.record(z.string().min(1), directories),\n});\n\ninterface ValidationOptions {\n path?: string;\n config?: string;\n dataset?: string[];\n allDatasets?: boolean;\n}\n\nexport async function resolveValidationTarget(\n options: ValidationOptions,\n): Promise<DatabaseConfig & { tableName?: string }> {\n if (options.dataset !== undefined && options.allDatasets) {\n throw new Error('Use either --dataset or --all-datasets, not both.');\n }\n if (options.path !== undefined) {\n if (options.config !== undefined || options.dataset !== undefined || options.allDatasets) {\n throw new Error('A file or directory path cannot be combined with dataset configuration options.');\n }\n const stats = await stat(options.path);\n if (stats.isDirectory()) return { dataDir: options.path };\n if (stats.isFile() && options.path.endsWith('.jsonl')) {\n return { dataDir: dirname(options.path), tableName: basename(options.path, '.jsonl') };\n }\n throw new Error(`Invalid path: ${options.path}. Must be a directory or .jsonl file.`);\n }\n\n return loadDatasetConfig(options.config, {\n datasets: options.allDatasets ? 'all' : options.dataset,\n });\n}\n\nexport interface DatasetConfigOptions {\n datasets?: string[] | 'all';\n}\n\nexport async function loadDatasetConfig(\n path = 'lines-db.config.json',\n options: DatasetConfigOptions = {},\n): Promise<DatabaseConfig> {\n const configPath = resolve(path);\n let config: z.infer<typeof datasetConfigSchema>;\n try {\n config = datasetConfigSchema.parse(JSON.parse(await readFile(configPath, 'utf-8')));\n } catch (error) {\n throw new Error(\n `Failed to load dataset configuration ${configPath}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n\n const names = options.datasets === 'all' ? Object.keys(config.datasets) : (options.datasets ?? []);\n const selected = names.flatMap((name) => {\n if (!Object.hasOwn(config.datasets, name)) {\n throw new Error(\n `Unknown dataset '${name}'. Available datasets: ${Object.keys(config.datasets).join(', ') || '(none)'}`,\n );\n }\n return config.datasets[name];\n });\n\n const configDir = dirname(configPath);\n const schemaDir = resolve(configDir, config.schemaDir);\n try {\n if (!(await stat(schemaDir)).isDirectory()) throw new Error('Expected a directory');\n } catch (error) {\n throw new Error(`Invalid schemaDir ${schemaDir}: ${error instanceof Error ? error.message : String(error)}`);\n }\n const dataDirs = await Promise.all([...config.base, ...selected].map((dir) => realpath(resolve(configDir, dir))));\n return {\n dataDir: [...new Set(dataDirs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AAI,IAAI,QAAQ,CAAC;EAC9B;CACF;AACF"}
1
+ {"version":3,"file":"index.mjs","names":["schema"],"sources":["../src/runtime.ts","../src/sqlite-adapter.ts","../src/jsonl-writer.ts","../src/schema-extensions.ts","../src/schema-loader.ts","../src/directory-scanner.ts","../src/schema.ts","../src/merge-fields.ts","../src/sql-statements.ts","../src/database.ts","../src/fill.ts","../src/type-generator.ts","../src/jsonl-migration.ts","../src/error-formatter.ts","../src/dataset-config.ts"],"sourcesContent":["/**\n * Runtime detection utilities\n */\n\nexport type RuntimeEnvironment = 'node' | 'unknown';\n\nexport function detectRuntime(): RuntimeEnvironment {\n // Check for Node.js\n if (typeof process !== 'undefined' && process.versions && process.versions.node) {\n return 'node';\n }\n\n return 'unknown';\n}\n\nexport const RUNTIME = detectRuntime();\n","/**\n * SQLite adapter for Node.js\n */\n\nimport { RUNTIME } from './runtime.js';\n\n/**\n * Common interface for SQLite database\n */\nexport interface SQLiteDatabase {\n prepare(sql: string): SQLiteStatement;\n exec(sql: string): void;\n close(): void;\n}\n\nexport interface SQLiteStatement {\n run(...params: any[]): { changes: number; lastInsertRowid: number | bigint };\n get(...params: any[]): any;\n all(...params: any[]): any[];\n}\n\n/**\n * Create a SQLite database instance for Node.js\n */\nexport function createDatabase(path: string = ':memory:'): SQLiteDatabase {\n if (RUNTIME === 'node') {\n return createNodeDatabase(path);\n } else {\n throw new Error(`Unsupported runtime: ${RUNTIME}`);\n }\n}\n\n/**\n * Create a Node.js SQLite database\n */\nfunction createNodeDatabase(path: string): SQLiteDatabase {\n // Dynamic import for Node.js\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { DatabaseSync } = require('node:sqlite');\n const db = new DatabaseSync(path);\n\n // CRITICAL: Enable foreign key constraints\n // SQLite disables foreign keys by default, which is a major data integrity issue\n db.exec('PRAGMA foreign_keys = ON');\n\n return {\n prepare(sql: string): SQLiteStatement {\n const stmt = db.prepare(sql);\n return {\n run(...params: any[]) {\n return stmt.run(...params);\n },\n get(...params: any[]) {\n return stmt.get(...params);\n },\n all(...params: any[]) {\n return stmt.all(...params);\n },\n };\n },\n exec(sql: string): void {\n db.exec(sql);\n },\n close(): void {\n db.close();\n },\n };\n}\n","import { writeFile } from 'node:fs/promises';\nimport type { JsonObject } from './types.js';\n\nexport class JsonlWriter {\n /**\n * Write data to JSONL file\n */\n static async write(filePath: string, data: JsonObject[]): Promise<void> {\n await writeFile(filePath, this.serialize(data), 'utf-8');\n }\n\n /**\n * The content {@link write} writes for the data\n */\n static serialize(data: JsonObject[]): string {\n return data.map((obj) => JSON.stringify(obj)).join('\\n') + '\\n';\n }\n\n /**\n * Append data to JSONL file\n */\n static async append(filePath: string, data: JsonObject[]): Promise<void> {\n const { readFile, writeFile } = await import('node:fs/promises');\n\n try {\n const existing = await readFile(filePath, 'utf-8');\n const lines = data.map((obj) => JSON.stringify(obj)).join('\\n');\n const newContent = existing.trim() + '\\n' + lines + '\\n';\n await writeFile(filePath, newContent, 'utf-8');\n } catch (error) {\n // If file doesn't exist, just write the data\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n await this.write(filePath, data);\n } else {\n throw error;\n }\n }\n }\n}\n","import { access } from 'node:fs/promises';\nimport { join } from 'node:path';\n\n/**\n * Supported schema file extensions, in priority order.\n * The first match wins when discovering schema files.\n */\nexport const SCHEMA_EXTENSIONS = ['.schema.ts', '.schema.mts', '.schema.cts'] as const;\nexport type SchemaExtension = (typeof SCHEMA_EXTENSIONS)[number];\n\n/**\n * Map from schema extensions to their JavaScript import counterparts.\n */\nconst SCHEMA_TO_JS_IMPORT_MAP: Record<string, string> = {\n '.schema.ts': '.schema.js',\n '.schema.mts': '.schema.mjs',\n '.schema.cts': '.schema.cjs',\n};\n\n/**\n * Try each supported schema extension and return the full path of the first\n * one that exists on disk. Returns undefined if none is found.\n */\nexport async function findSchemaFile(dir: string, tableName: string): Promise<string | undefined> {\n for (const ext of SCHEMA_EXTENSIONS) {\n const candidate = join(dir, `${tableName}${ext}`);\n try {\n await access(candidate);\n return candidate;\n } catch {\n // Continue to next extension\n }\n }\n return undefined;\n}\n\n/**\n * Synchronously find a schema file among directory entries.\n * Returns the full path of the first match, or undefined.\n */\nexport function findSchemaFileInEntries(\n dataDirPath: string,\n tableName: string,\n entries: { isFile(): boolean; name: string }[],\n): string | undefined {\n for (const ext of SCHEMA_EXTENSIONS) {\n const candidateName = `${tableName}${ext}`;\n if (entries.some((e) => e.isFile() && e.name === candidateName)) {\n return join(dataDirPath, candidateName);\n }\n }\n return undefined;\n}\n\n/**\n * Check if a filename matches any supported schema file pattern.\n */\nexport function isSchemaFile(fileName: string): boolean {\n return SCHEMA_EXTENSIONS.some((ext) => fileName.endsWith(ext));\n}\n\n/**\n * Extract table name from a schema filename.\n * e.g., \"users.schema.ts\" -> \"users\", \"users.schema.mts\" -> \"users\"\n */\nexport function extractTableNameFromSchemaFile(fileName: string): string | null {\n for (const ext of SCHEMA_EXTENSIONS) {\n if (fileName.endsWith(ext)) {\n return fileName.slice(0, -ext.length);\n }\n }\n return null;\n}\n\n/**\n * Rewrite a TypeScript path to its JavaScript counterpart for ESM imports.\n * \".schema.ts\" -> \".schema.js\", \".schema.mts\" -> \".schema.mjs\", \".schema.cts\" -> \".schema.cjs\"\n */\nexport function rewriteExtensionForImport(filePath: string): string {\n for (const [tsExt, jsExt] of Object.entries(SCHEMA_TO_JS_IMPORT_MAP)) {\n if (filePath.endsWith(tsExt)) {\n return filePath.slice(0, -tsExt.length) + jsExt;\n }\n }\n return filePath;\n}\n","import { dirname, basename } from 'node:path';\nimport type { StandardSchema } from './types.js';\nimport { findSchemaFile, SCHEMA_EXTENSIONS } from './schema-extensions.js';\nimport { createSchemaImports, type SchemaImports } from './schema-module.js';\n\nexport class SchemaLoader {\n /**\n * Check if a schema file exists for a table\n */\n static async hasSchema(jsonlPath: string, schemaDir?: string): Promise<boolean> {\n const dir = schemaDir ?? dirname(jsonlPath);\n const tableName = basename(jsonlPath, '.jsonl');\n const schemaPath = await findSchemaFile(dir, tableName);\n return schemaPath !== undefined;\n }\n\n /**\n * Load a validation schema file for a table\n * Requires ${tableName}.schema.{ts,mts,cts} to exist in schemaDir, or alongside the JSONL file when omitted\n */\n static async loadSchema(jsonlPath: string, schemaDir?: string, imports?: SchemaImports): Promise<StandardSchema> {\n const dir = schemaDir ?? dirname(jsonlPath);\n const tableName = basename(jsonlPath, '.jsonl');\n const schemaPath = await findSchemaFile(dir, tableName);\n\n if (!schemaPath) {\n throw new Error(\n `Schema file not found for table '${tableName}'. Expected one of: ${SCHEMA_EXTENSIONS.map((ext) => `${tableName}${ext}`).join(', ')}`,\n );\n }\n\n try {\n const module = await (imports ?? createSchemaImports()).import(schemaPath);\n const schema = module.default || module.schema;\n\n if (schema && this.isStandardSchema(schema)) {\n return schema;\n }\n\n throw new Error(`Schema file ${schemaPath} does not export a valid StandardSchema`);\n } catch (error) {\n throw new Error(\n `Failed to load schema for table '${tableName}' from ${schemaPath}: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error instanceof Error ? error : undefined },\n );\n }\n }\n\n /**\n * Check if an object implements the StandardSchema interface\n */\n private static isStandardSchema(obj: unknown): obj is StandardSchema {\n if (!obj || typeof obj !== 'object') return false;\n\n const schema = obj as Record<string, unknown>;\n const standard = schema['~standard'];\n\n if (!standard || typeof standard !== 'object') return false;\n\n const standardObj = standard as Record<string, unknown>;\n\n return (\n standardObj.version === 1 && typeof standardObj.vendor === 'string' && typeof standardObj.validate === 'function'\n );\n }\n}\n","import { readdir } from 'node:fs/promises';\nimport { join, basename, extname } from 'node:path';\nimport type { TableConfig } from './types.js';\n\nexport class DirectoryScanner {\n /**\n * Scan directories for JSONL files and create table configurations.\n * A table found in several directories lists its files in the order the directories are given.\n */\n static async scanDirectory(dataDir: string | readonly string[]): Promise<Map<string, TableConfig>> {\n const dataDirs = typeof dataDir === 'string' ? [dataDir] : dataDir;\n const jsonlPathsByTable = new Map<string, string[]>();\n\n for (const dir of dataDirs) {\n let files: string[];\n try {\n files = await readdir(dir);\n } catch (error) {\n throw new Error(`Failed to scan directory ${dir}: ${error instanceof Error ? error.message : String(error)}`);\n }\n\n for (const file of files) {\n if (extname(file) === '.jsonl') {\n const tableName = basename(file, '.jsonl');\n const jsonlPaths = jsonlPathsByTable.get(tableName) ?? [];\n jsonlPaths.push(join(dir, file));\n jsonlPathsByTable.set(tableName, jsonlPaths);\n }\n }\n }\n\n if (jsonlPathsByTable.size === 0) {\n console.warn(`Warning: No JSONL files found in directory: ${dataDirs.join(', ')}`);\n }\n\n const tables = new Map<string, TableConfig>();\n for (const [tableName, jsonlPaths] of jsonlPathsByTable) {\n tables.set(tableName, { jsonlPath: jsonlPaths[0], jsonlPaths, autoInferSchema: true });\n }\n return tables;\n }\n}\n","import type { StandardSchema, Table, ForeignKeyDefinition, IndexDefinition } from './types.js';\n\n/**\n * Schema options for defining constraints and indexes\n * When Input and Output types differ, backward transformation is required\n */\nexport type SchemaOptions<Input extends Table, Output extends Table> = {\n /**\n * Primary key column\n */\n primaryKey?: string;\n\n /**\n * Foreign key constraints\n */\n foreignKeys?: ForeignKeyDefinition[];\n\n /**\n * Indexes to create\n */\n indexes?: IndexDefinition[];\n} & (Output extends Input\n ? {\n /**\n * Backward transformation from Output to Input (optional when output is substitutable for input)\n */\n backward?: (output: Output) => Input;\n }\n : {\n /**\n * Backward transformation from Output to Input (REQUIRED when types differ)\n */\n backward: (output: Output) => Input;\n });\n\n/**\n * BiDirectional Schema interface\n * Extends StandardSchema with optional backward transformation and schema metadata\n */\nexport interface BiDirectionalSchema<Input extends Table = Table, Output extends Table = Input> extends StandardSchema<\n Input,\n Output\n> {\n /**\n * Backward transformation from Output to Input\n * Required when Input and Output types differ (e.g., with transformations)\n */\n backward?: (output: Output) => Input;\n\n /**\n * Primary key column\n */\n primaryKey?: string;\n\n /**\n * Foreign key constraints\n */\n foreignKeys?: ForeignKeyDefinition[];\n\n /**\n * Indexes to create\n */\n indexes?: IndexDefinition[];\n}\n\n/**\n * Define a bidirectional schema with optional backward transformation\n *\n * @param schema - Standard Schema for validation\n * @param options - SchemaOptions object. When Input and Output types differ, backward transformation is required\n *\n * @example\n * // No transformation - backward not needed\n * const schema = defineSchema(\n * v.object({ id: v.number(), name: v.string() })\n * );\n *\n * @example\n * // With transformation - backward REQUIRED\n * const schema = defineSchema(\n * v.pipe(v.string(), v.transform(Number)),\n * {\n * backward: (num) => String(num) // backward: number → string (REQUIRED)\n * }\n * );\n *\n * @example\n * // With primary key and foreign key\n * const schema = defineSchema(\n * v.object({ id: v.number(), customerId: v.number() }),\n * {\n * primaryKey: 'id',\n * foreignKeys: [\n * { column: 'customerId', references: { table: 'users', column: 'id' } }\n * ]\n * }\n * );\n */\nexport function defineSchema<Input extends Table, Output extends Table>(\n schema: StandardSchema<Input, Output>,\n ...args: Output extends Input ? [options?: SchemaOptions<Input, Output>] : [options: SchemaOptions<Input, Output>]\n): BiDirectionalSchema<Input, Output> {\n const options = args[0];\n // Create a new object that extends the schema\n const bidirectionalSchema = Object.create(schema) as BiDirectionalSchema<Input, Output>;\n\n // Handle options object\n if (options) {\n if (options.backward) {\n bidirectionalSchema.backward = options.backward as (output: Output) => Input;\n }\n if (options.primaryKey) {\n bidirectionalSchema.primaryKey = options.primaryKey;\n }\n if (options.foreignKeys) {\n bidirectionalSchema.foreignKeys = options.foreignKeys;\n }\n if (options.indexes) {\n bidirectionalSchema.indexes = options.indexes;\n }\n }\n\n // Copy '~standard' property\n Object.defineProperty(bidirectionalSchema, '~standard', {\n value: schema['~standard'],\n enumerable: true,\n configurable: true,\n });\n\n return bidirectionalSchema;\n}\n\n/**\n * Check if a schema has backward transformation\n */\nexport function hasBackward<Input extends Table, Output extends Table>(\n schema: StandardSchema<Input, Output>,\n): schema is BiDirectionalSchema<Input, Output> {\n return 'backward' in schema && typeof (schema as { backward?: unknown }).backward === 'function';\n}\n","import type { JsonObject, JsonValue } from './types.js';\n\n/**\n * Options for {@link mergeFields}\n */\nexport interface MergeFieldsOptions {\n /**\n * Fields taken from the computed row. Every other field keeps the value the line holds.\n * A field the computed row has no value for is not written, so the line keeps what it has rather\n * than having a null written over it.\n */\n fields: readonly string[];\n\n /**\n * The order fields are declared in, used to place a field the line did not have.\n * Defaults to the order the computed row lists its own fields in - a row a schema computed lists\n * them the way that schema declares them.\n */\n keyOrder?: Iterable<string>;\n}\n\n/**\n * Lay the named fields of a computed row over the line a JSONL file already holds.\n *\n * A field the line did not have is inserted where the schema declares it rather than appended, so a\n * filled-in `id` lands at the front of the line the way a hand-written row has it. No key the line\n * already had moves, and a key the schema does not declare stays behind the declared ones.\n *\n * @param line - The row as the JSONL file holds it\n * @param computed - The row a schema computed from it, which the named fields are taken from. Only its\n * own fields count: a field the schema does not produce is left to the line even when a name like\n * `toString` would resolve to something on `Object.prototype`. A field it holds as `undefined` is\n * left to the line as well.\n * @param options - The fields to take, and the order they are declared in\n * @returns A new row: the line, with the named fields written into it\n *\n * @example\n * // line: {\"name\":\"Alice\",\"note\":\"check\"}\n * // computed: {\"id\":\"018f…\",\"name\":\"Alice\",\"createdAt\":\"2026-…\"}\n * mergeFields(line, computed, { fields: ['id', 'createdAt'] });\n * // {\"id\":\"018f…\",\"name\":\"Alice\",\"createdAt\":\"2026-…\",\"note\":\"check\"}\n */\nexport function mergeFields(\n line: JsonObject,\n computed: Record<string, JsonValue | undefined>,\n options: MergeFieldsOptions,\n): JsonObject {\n const rank = new Map<string, number>();\n for (const key of options.keyOrder ?? Object.keys(computed)) {\n // The first mention wins, so a key the order lists twice keeps its earliest place\n if (!rank.has(key)) {\n rank.set(key, rank.size);\n }\n }\n // A key the schema does not declare ranks past every declared one, and so keeps its place\n const rankOf = (key: string): number => rank.get(key) ?? Number.MAX_SAFE_INTEGER;\n\n const written = new Map<string, JsonValue>();\n for (const field of options.fields) {\n // `Object.hasOwn`, not a check on the value: a field named `toString` would otherwise take what\n // `Object.prototype` holds. A field the computed row has as undefined is left to the line too,\n // since writing undefined would drop the key entirely\n if (Object.hasOwn(computed, field) && computed[field] !== undefined) {\n written.set(field, computed[field]);\n }\n }\n\n // `Object.hasOwn`, not `field in line`: a field named `toString` would otherwise read as present\n const inserted = Array.from(written.keys())\n .filter((field) => !Object.hasOwn(line, field))\n .sort((a, b) => rankOf(a) - rankOf(b));\n\n const entries: [string, JsonValue][] = [];\n for (const key of Object.keys(line)) {\n while (inserted.length > 0 && rankOf(inserted[0]) < rankOf(key)) {\n const field = inserted.shift()!;\n entries.push([field, written.get(field)!]);\n }\n entries.push([key, written.has(key) ? written.get(key)! : line[key]]);\n }\n for (const field of inserted) {\n entries.push([field, written.get(field)!]);\n }\n\n // Not an object literal with assignments: a line holding `__proto__` or `toString` keeps that key\n return Object.fromEntries(entries);\n}\n\n/**\n * The row with the fields its line holds that the table has no column for - a schema that strips\n * unknown keys lets them through - kept where the line holds them, so writing back does not drop them\n */\nexport function keepUnknownFields(line: JsonObject, row: JsonObject, columns: ReadonlySet<string>): JsonObject {\n const unknown = Object.keys(line).filter((key) => !columns.has(key) && !Object.hasOwn(row, key));\n if (unknown.length === 0) return row;\n const entries: Array<[string, JsonValue]> = [];\n for (const key of Object.keys(line)) {\n if (Object.hasOwn(row, key)) entries.push([key, row[key]]);\n else if (unknown.includes(key)) entries.push([key, line[key]]);\n }\n for (const key of Object.keys(row)) if (!Object.hasOwn(line, key)) entries.push([key, row[key]]);\n // Not assigned to an object literal: a key named `__proto__` would set the prototype instead\n return Object.fromEntries(entries);\n}\n","const TRIGGER_DEFINITION = /^\\s*CREATE\\s+(?:TEMP(?:ORARY)?\\s+)?TRIGGER\\b/i;\nconst CLOSER: Record<string, string> = { \"'\": \"'\", '\"': '\"', '`': '`', '[': ']' };\n\n/**\n * Split SQL text into its statements at `;`, the way SQLite reads it: a `;` inside a comment or quoted\n * text does not end a statement, and a comment is left out as the whitespace it is\n */\nexport function splitStatements(sql: string): string[] {\n const statements: string[] = [];\n let current = '';\n let i = 0;\n while (i < sql.length) {\n const char = sql[i]!;\n if (char === '-' && sql[i + 1] === '-') {\n const end = sql.indexOf('\\n', i);\n i = end === -1 ? sql.length : end;\n current += ' ';\n } else if (char === '/' && sql[i + 1] === '*') {\n const end = sql.indexOf('*/', i + 2);\n i = end === -1 ? sql.length : end + 2;\n current += ' ';\n } else if (char in CLOSER) {\n // A doubled quote inside is read as a closing one followed by an opening one, which copies the same\n const end = sql.indexOf(CLOSER[char]!, i + 1);\n const stop = end === -1 ? sql.length : end + 1;\n current += sql.slice(i, stop);\n i = stop;\n } else if (char === ';' && !insideTriggerBody(current)) {\n statements.push(current);\n current = '';\n i += 1;\n } else {\n current += char;\n i += 1;\n }\n }\n statements.push(current);\n return statements.map((statement) => statement.trim()).filter((statement) => statement.length > 0);\n}\n\n/**\n * Whether a `;` after this text is inside the body of a trigger, which only a `;` followed by `END` and\n * another `;` closes. Only an END right after a `;` counts, as the END of a CASE in the body does not\n */\nfunction insideTriggerBody(statement: string): boolean {\n return TRIGGER_DEFINITION.test(statement) && !/;\\s*END$/i.test(statement.trimEnd());\n}\n\nconst READ_STATEMENTS = new Set(['SELECT', 'VALUES', 'WITH', 'EXPLAIN']);\n\n// A pragma that takes an argument and only reads: PRAGMA table_info(tags)\nconst READ_PRAGMAS_WITH_ARGUMENT = new Set([\n 'table_info',\n 'table_xinfo',\n 'table_list',\n 'index_list',\n 'index_info',\n 'index_xinfo',\n 'foreign_key_list',\n 'foreign_key_check',\n 'integrity_check',\n 'quick_check',\n 'collation_list',\n 'database_list',\n 'function_list',\n 'module_list',\n 'pragma_list',\n 'compile_options',\n]);\n\n// A pragma that reads when bare and sets when given a value or an argument: PRAGMA user_version(5) sets it\nconst READ_PRAGMAS_BARE = new Set([\n 'query_only',\n 'user_version',\n 'application_id',\n 'schema_version',\n 'foreign_keys',\n 'journal_mode',\n 'page_count',\n 'page_size',\n 'freelist_count',\n 'encoding',\n 'data_version',\n]);\n\nconst PRAGMA_NAME = String.raw`(?:\\w+|\"[^\"]*\"|'[^']*'|\\x60[^\\x60]*\\x60|\\[[^\\]]*\\])`;\nconst PRAGMA_STATEMENT = new RegExp(\n String.raw`^PRAGMA\\s+(?:${PRAGMA_NAME}\\s*\\.\\s*)?(${PRAGMA_NAME})\\s*(\\(.*\\))?$`,\n 'is',\n);\n\n/**\n * Whether a statement, as {@link splitStatements} returns it, only reads. Closed by default: whatever is\n * not known to read is refused, so a statement or pragma added to SQLite later is refused too. A WITH\n * can wrap a write, which the read-only mode of the connection is left to refuse\n */\nexport function isReadOnlyStatement(statement: string): boolean {\n const keyword = /^[A-Za-z]+/.exec(statement)?.[0]?.toUpperCase();\n if (keyword === undefined) return false;\n if (READ_STATEMENTS.has(keyword)) return true;\n if (keyword !== 'PRAGMA') return false;\n\n const match = PRAGMA_STATEMENT.exec(statement);\n if (!match) return false;\n const name = match[1]!.replace(/^[\"'`[]|[\"'`\\]]$/g, '').toLowerCase();\n const argument = match[2];\n if (READ_PRAGMAS_WITH_ARGUMENT.has(name)) return true;\n return READ_PRAGMAS_BARE.has(name) && argument === undefined;\n}\n","import { createDatabase, type SQLiteDatabase } from './sqlite-adapter.js';\nimport { JsonlReader, hashJsonlContent } from './jsonl-reader.js';\nimport { JsonlWriter } from './jsonl-writer.js';\nimport { replaceFile } from './replace-file.js';\nimport { SchemaLoader } from './schema-loader.js';\nimport { createSchemaImports, hashContent, MISSING_HASH, type SchemaImports } from './schema-module.js';\nimport { DirectoryScanner } from './directory-scanner.js';\nimport { hasBackward } from './schema.js';\nimport { keepUnknownFields, mergeFields } from './merge-fields.js';\nimport { findSchemaFile } from './schema-extensions.js';\nimport { readFile, rm, writeFile } from 'node:fs/promises';\nimport { randomBytes } from 'node:crypto';\nimport { dirname, join, resolve } from 'node:path';\nimport type {\n DatabaseConfig,\n TableSchema,\n ColumnDefinition,\n JsonObject,\n TableConfig,\n StandardSchema,\n ValidationError,\n JsonlConflictError,\n Table,\n TableDefs,\n WriteFilledValues,\n WhereCondition,\n ValidationResult,\n ValidationErrorDetail,\n TableValidationResult,\n ForeignKeyDefinition,\n} from './types.js';\nimport type { BiDirectionalSchema } from './schema.js';\nimport { type Result, ok, err, toError, unwrap } from './result.js';\nimport { isReadOnlyStatement, splitStatements } from './sql-statements.js';\n\n/**\n * Options for {@link LinesDB.update}\n */\nexport interface UpdateOptions {\n /** Validate each updated row against the table's schema. Defaults to true */\n validate?: boolean;\n /**\n * Fields to leave to the schema: each updated row stores the value its schema fills in for them, and\n * a write-back removes them from the row's line\n */\n resetToDefault?: readonly string[];\n}\n\n/**\n * Options for {@link LinesDB.sync}\n */\nexport interface SyncOptions {\n /**\n * Fields written back to the JSONL file.\n * When provided, only these fields are taken from the database and merged into the matching\n * JSONL line; every other field keeps the value the file already had. An empty list takes no\n * field from the database, so existing lines keep every value they hold - rows added to or\n * removed from the database are still reflected.\n * Defaults to `writeBackFields` from the database config, or writing every field of the row.\n */\n fields?: readonly string[];\n /**\n * Which values the validation schema fills in to write into the file.\n * Defaults to `writeFilledValues` from the database config, or `'all'`.\n */\n writeFilledValues?: WriteFilledValues;\n}\n\n/**\n * Sync options plus how to treat fields a table does not have: a sync asked for one table by name\n * rejects them, while a sync covering every table just leaves them out.\n */\ntype InternalSyncOptions = SyncOptions & { strictFields?: boolean };\n\n/** The rows a table is about to be written back as, and what its file held before */\ninterface PreparedWriteBack {\n tableName: string;\n jsonlPath: string;\n rows: JsonObject[];\n /** Undefined when the file did not exist */\n previousContent: string | undefined;\n /** How many changes the table had seen when its rows were read */\n generation: number;\n rowids?: string[];\n unchanged?: boolean;\n completed?: boolean;\n}\n\n/** The fields set and reset on a row since its table was last written back */\ninterface FieldChanges {\n set: Set<string>;\n reset: Set<string>;\n /** Whether the row was inserted, rather than read from a line */\n inserted: boolean;\n}\n\nfunction cloneFieldChanges(changes: Map<string, Map<string, FieldChanges>>): Map<string, Map<string, FieldChanges>> {\n return new Map(\n Array.from(changes, ([tableName, byRow]) => [\n tableName,\n new Map(\n Array.from(byRow, ([rowid, row]) => [\n rowid,\n { set: new Set(row.set), reset: new Set(row.reset), inserted: row.inserted },\n ]),\n ),\n ]),\n );\n}\n\n/** Column alias a query reads a row's rowid under, next to its fields */\nconst ROWID_ALIAS = '__lines_db_rowid';\n\n/** The fields a row given to an insert names, leaving out those it leaves undefined */\nfunction givenFields(row: object): string[] {\n return Object.entries(row)\n .filter(([, value]) => value !== undefined)\n .map(([key]) => key);\n}\n\n/** Whether a value read from SQLite and one about to be stored are the same */\nfunction sameStoredValue(stored: unknown, next: unknown): boolean {\n if (stored === null || stored === undefined || next === null) return (stored ?? null) === next;\n return String(stored) === String(next);\n}\n\n/** The JSONL file a row was read from, and its index among that file's rows */\ninterface RowOrigin {\n file: string;\n rowIndex: number;\n}\n\nexport class LinesDB<Tables extends TableDefs> {\n private db: SQLiteDatabase;\n private readonly rowMovesTable = `__lines_db_moves_${randomBytes(12).toString('hex')}`;\n private config: DatabaseConfig<Tables>;\n private schemas: Map<string, TableSchema> = new Map();\n private validationSchemas: Map<string, StandardSchema | undefined> = new Map();\n private tables: Map<string, TableConfig> = new Map();\n private inTransaction: boolean = false;\n private syncQueue: Map<string, Promise<void>> = new Map();\n /** The order a table's schema declares its fields in, as the rows it computes list them */\n private keyOrders: Map<string, Set<string>> = new Map();\n /** The row each rowid was inserted from, per table loaded with detailed validation */\n private rowOriginsByRowid: Map<string, Map<string, RowOrigin>> = new Map();\n /**\n * The fields set and reset on each row (by rowid) since its table was last written back: a line\n * holds the fields a user wrote, so only what changed since it was written needs remembering\n */\n private fieldChanges: Map<string, Map<string, FieldChanges>> = new Map();\n private settleUndos: Array<() => void> | undefined;\n /**\n * The tables raw SQL may have changed since they were last written back: which fields it set is\n * unknown, so their rows are written back whole\n */\n private rawSqlTables: Set<string> = new Set();\n /** How many changes each table has seen, which tells a write-back whether one came after it read the rows */\n private changeGenerations: Map<string, number> = new Map();\n /**\n * The lines read, by rowid, that hold a field the table has no column for: kept to write that field\n * back, also once the row's primary key changed and its line can no longer be found by it\n */\n private linesWithUnknownFields: Map<string, Map<string, JsonObject>> = new Map();\n /** Whether a transaction's callback has returned and its files are being written back */\n private transactionClosing = false;\n /** Whether a transaction() call is past its guard but has not begun yet */\n private transactionStarting = false;\n /** Whether the running call came in through the object the running transaction() callback receives */\n private viaTransactionObject = false;\n /** Identifies the running transaction, so an object kept from an earlier one is not taken for its own */\n private transactionToken: object | undefined;\n /** The tables changed in the running transaction, or 'all' once raw SQL may have changed any */\n private transactionChanges: Set<string> | 'all' | undefined;\n /** Hash of each JSONL file's content as this database last read or wrote it */\n private fileHashes: Map<string, string> = new Map();\n /**\n * Hash of each JSONL file's content as this database last read or wrote it, kept for a table that\n * failed to load too: unlike fileHashes, it only tells whether a file changed and guards no write\n */\n private observedHashes: Map<string, string> = new Map();\n /** The JSONL files the data directories held when the tables were scanned */\n private scannedJsonlFiles: string[] = [];\n /** Tables left out because their files have no rows to infer the columns from */\n private emptyTables: Set<string> = new Set();\n /** Tables created from the columns `schemaOfEmptyTable` gave, which may lack a field the validator adds */\n private tablesFromGivenColumns: Set<string> = new Set();\n /** Each table's schema file and a hash of its content as the tables were loaded, or '' for none */\n private schemaFileStates: Map<string, string> = new Map();\n // The imports of the schema files of one load, which evaluate a project file they share once\n private schemaImports: SchemaImports | undefined;\n // The files the schemas import, with what they held when read: an edit to one changes what a table validates\n private schemaDependencyHashes: Map<string, Map<string, string>> = new Map();\n\n private constructor(config: DatabaseConfig<Tables>, dbPath?: string) {\n this.config = config;\n this.db = createDatabase(dbPath ?? ':memory:');\n }\n\n static create<Tables extends TableDefs>(config: DatabaseConfig<Tables>, dbPath?: string): LinesDB<Tables> {\n return new LinesDB<Tables>(config, dbPath);\n }\n\n /**\n * Initialize database by loading all JSONL files or a specific table\n * Uses dependency resolution to ensure foreign key references are loaded in correct order\n * @param options Optional configuration for initialization\n * @param options.tableName Optional table name to initialize. If not provided, initializes all tables\n * @param options.detailedValidate If true, performs detailed validation by inserting rows one by one to catch constraint violations\n * @param options.transform Optional transform function to apply to rows before validation (only applied to the specified tableName)\n * @returns Result wrapping a ValidationResult with validation status, errors, and warnings\n */\n async initialize(options?: {\n tableName?: string;\n detailedValidate?: boolean;\n transform?: (row: JsonObject) => JsonObject;\n }): Promise<Result<ValidationResult, Error>> {\n try {\n return ok(await this.initializeInternal(options));\n } catch (error) {\n return err(toError(error));\n }\n }\n\n private async initializeInternal(options?: {\n tableName?: string;\n detailedValidate?: boolean;\n transform?: (row: JsonObject) => JsonObject;\n }): Promise<ValidationResult> {\n if (this.hasSeveralDataDirs() && !this.config.schemaDir) {\n throw new Error(\n 'schemaDir is required when dataDir lists several directories: a data set directory does not hold the schemas of its tables',\n );\n }\n\n this.db.exec('PRAGMA query_only = OFF');\n try {\n return await this.loadTables(options);\n } finally {\n // Raw SQL through execute() or query() must not change a database whose changes cannot be written back\n if (this.isReadOnlyDataSet()) {\n this.db.exec('PRAGMA query_only = ON');\n }\n }\n }\n\n private async loadTables(options?: {\n tableName?: string;\n detailedValidate?: boolean;\n transform?: (row: JsonObject) => JsonObject;\n }): Promise<ValidationResult> {\n const allErrors: ValidationErrorDetail[] = [];\n const allWarnings: string[] = [];\n const allRowCounts = new Map<string, number>();\n const tableName = options?.tableName;\n const detailedValidate = options?.detailedValidate ?? false;\n const transform = options?.transform;\n\n // Scan directory for JSONL files\n this.emptyTables.clear();\n this.tables = await DirectoryScanner.scanDirectory(this.config.dataDir);\n this.scannedJsonlFiles = listJsonlFiles(this.tables);\n this.observedHashes.clear();\n this.schemaFileStates.clear();\n for (const [name, config] of this.tables) {\n this.schemaFileStates.set(name, await this.schemaFileState(name, config));\n }\n\n // Determine which tables to load\n const tablesToLoad = tableName ? [tableName] : Array.from(this.tables.keys());\n for (const name of tablesToLoad) this.tablesFromGivenColumns.delete(name);\n\n // Validate that all requested tables exist BEFORE starting to load\n for (const tableNameToLoad of tablesToLoad) {\n if (!this.tables.has(tableNameToLoad)) {\n const dataDirs = [this.config.dataDir].flat().map((dir) => `'${dir}'`);\n throw new Error(`Table '${tableNameToLoad}' not found in directory ${dataDirs.join(', ')}`);\n }\n }\n\n // Track loaded tables and tables currently being loaded (for circular dependency detection)\n const loadedTables = new Set<string>();\n const loadingTables = new Set<string>();\n const attemptedTables = new Set<string>(); // Track all attempted tables (loaded or not)\n const allDeferredForeignKeys: Array<{\n tableName: string;\n foreignKey: ForeignKeyDefinition;\n filePath: string;\n }> = [];\n\n // Load tables with dependency resolution\n const imports = createSchemaImports();\n this.schemaImports = imports;\n // Taken before the tables are read: a table that fails to load is dropped from `this.tables`, and its imports still matter\n const schemaPaths = new Map<string, string>();\n for (const [name, config] of this.tables) {\n const schemaPath = await this.findTableSchemaFile(name, config);\n if (schemaPath) schemaPaths.set(name, schemaPath);\n }\n try {\n for (const tableNameToLoad of tablesToLoad) {\n if (!attemptedTables.has(tableNameToLoad)) {\n // Only apply transform to the specified table\n const tableTransform = tableNameToLoad === tableName ? transform : undefined;\n const {\n errors,\n warnings,\n rowCounts: tableRowCounts,\n deferredForeignKeys,\n } = await this.loadTableWithDependencies(\n tableNameToLoad,\n loadedTables,\n loadingTables,\n attemptedTables,\n detailedValidate,\n tableTransform,\n );\n allErrors.push(...errors);\n allWarnings.push(...warnings);\n allDeferredForeignKeys.push(...deferredForeignKeys);\n for (const [k, v] of tableRowCounts) {\n allRowCounts.set(k, v);\n }\n }\n }\n } finally {\n this.schemaImports = undefined;\n this.recordSchemaDependencies(imports, attemptedTables, schemaPaths, tableName === undefined);\n }\n\n // Validate deferred foreign keys (from circular dependencies) now that all tables are loaded\n if (detailedValidate && allDeferredForeignKeys.length > 0) {\n for (const { tableName: tName, foreignKey: fk, filePath } of allDeferredForeignKeys) {\n // Only validate if the referenced table was actually loaded\n if (!loadedTables.has(fk.references.table)) {\n continue;\n }\n const deferredErrors = this.validateDeferredForeignKey(tName, fk, filePath);\n allErrors.push(...deferredErrors);\n }\n }\n\n // Build per-table results\n const tableResults: TableValidationResult[] = tablesToLoad.map((name) => {\n const tableErrors = allErrors.filter((e) => e.tableName === name);\n const tableWarnings = allWarnings.filter((w) => w.includes(`'${name}'`));\n return {\n tableName: name,\n valid: tableErrors.length === 0,\n rowCount: allRowCounts.get(name) ?? 0,\n errors: tableErrors,\n warnings: tableWarnings,\n };\n });\n\n return {\n valid: allErrors.length === 0,\n errors: allErrors,\n warnings: allWarnings,\n tableResults,\n };\n }\n\n private importSchemaModule(schemaPath: string): Promise<Record<string, any>> {\n return (this.schemaImports ?? createSchemaImports()).import(schemaPath);\n }\n\n /**\n * Load a table and its dependencies recursively\n */\n private async loadTableWithDependencies(\n tableName: string,\n loadedTables: Set<string>,\n loadingTables: Set<string>,\n attemptedTables: Set<string>,\n detailedValidate: boolean,\n transform?: (row: JsonObject) => JsonObject,\n ): Promise<{\n errors: ValidationErrorDetail[];\n warnings: string[];\n rowCounts: Map<string, number>;\n deferredForeignKeys: Array<{\n tableName: string;\n foreignKey: ForeignKeyDefinition;\n filePath: string;\n }>;\n }> {\n const errors: ValidationErrorDetail[] = [];\n const warnings: string[] = [];\n const rowCounts = new Map<string, number>();\n const deferredForeignKeys: Array<{\n tableName: string;\n foreignKey: ForeignKeyDefinition;\n filePath: string;\n }> = [];\n\n // Skip if already attempted (loaded or not)\n if (attemptedTables.has(tableName)) {\n return { errors, warnings, rowCounts, deferredForeignKeys };\n }\n\n // Mark as attempted\n attemptedTables.add(tableName);\n\n // Check for circular dependencies\n if (loadingTables.has(tableName)) {\n throw new Error(`Circular dependency detected for table '${tableName}'`);\n }\n\n // Get table config\n const tableConfig = this.tables.get(tableName);\n if (!tableConfig) {\n throw new Error(`Table configuration not found for '${tableName}'`);\n }\n\n // Mark as currently loading\n loadingTables.add(tableName);\n\n try {\n // Load schema module to check for foreign key dependencies\n // We need to load the entire module to access foreignKeys export\n let foreignKeys: BiDirectionalSchema['foreignKeys'];\n\n try {\n const schemaPath = await this.findTableSchemaFile(tableName, tableConfig);\n if (schemaPath) {\n const schemaModule = await this.importSchemaModule(schemaPath);\n\n // Try to get foreign keys from exported 'schema' or directly from module\n const schemaExport = schemaModule.schema || schemaModule.default;\n foreignKeys = schemaExport?.foreignKeys || schemaModule.foreignKeys;\n }\n } catch {\n // Schema file not found - will continue without validation\n }\n\n // If there are foreign key dependencies, load them first\n if (foreignKeys && foreignKeys.length > 0) {\n for (const fk of foreignKeys) {\n const referencedTable = fk.references.table;\n\n // Skip self-referencing foreign keys (e.g., nullable parent_id columns)\n if (referencedTable === tableName) {\n continue;\n }\n\n if (!attemptedTables.has(referencedTable)) {\n // Check if referenced table exists in our tables map\n if (this.tables.has(referencedTable)) {\n // Dependencies should not have transform applied\n const depResult = await this.loadTableWithDependencies(\n referencedTable,\n loadedTables,\n loadingTables,\n attemptedTables,\n detailedValidate,\n undefined,\n );\n errors.push(...depResult.errors);\n warnings.push(...depResult.warnings);\n deferredForeignKeys.push(...depResult.deferredForeignKeys);\n for (const [k, v] of depResult.rowCounts) {\n rowCounts.set(k, v);\n }\n } else {\n throw new Error(\n `Foreign key reference to non-existent table '${referencedTable}' in table '${tableName}'`,\n );\n }\n }\n }\n }\n\n // Determine which FK dependencies failed or are circular (attempted but not loaded)\n const failedDependencies = new Set<string>();\n const circularDependencies = new Set<string>();\n if (foreignKeys && foreignKeys.length > 0) {\n for (const fk of foreignKeys) {\n const referencedTable = fk.references.table;\n if (referencedTable === tableName) continue;\n if (attemptedTables.has(referencedTable) && !loadedTables.has(referencedTable)) {\n if (loadingTables.has(referencedTable)) {\n // Circular dependency: table is currently being loaded\n circularDependencies.add(referencedTable);\n } else {\n // Actual failure: table attempted but not loaded\n failedDependencies.add(referencedTable);\n }\n }\n }\n if (failedDependencies.size > 0) {\n for (const dep of failedDependencies) {\n const reason = this.emptyTables.has(dep) ? 'has no rows to read its columns from' : 'has validation errors';\n warnings.push(\n `Skipping foreign key validation for table '${tableName}': referenced table '${dep}' ${reason}`,\n );\n }\n }\n }\n\n // Combine failed and circular dependencies for table loading (both need FK skipping)\n const allSkippedDependencies = new Set([...failedDependencies, ...circularDependencies]);\n\n // Now load this table\n const {\n loaded,\n rowCount,\n errors: loadErrors,\n } = await this.loadTable(tableName, tableConfig, detailedValidate, transform, allSkippedDependencies);\n errors.push(...loadErrors);\n rowCounts.set(tableName, rowCount);\n\n if (loaded) {\n loadedTables.add(tableName);\n\n // Track circular dependency FKs for deferred validation\n if (foreignKeys && circularDependencies.size > 0) {\n for (const fk of foreignKeys) {\n if (circularDependencies.has(fk.references.table)) {\n deferredForeignKeys.push({\n tableName,\n foreignKey: fk,\n filePath: tableConfig.jsonlPath,\n });\n }\n }\n }\n } else {\n // Table was not loaded (e.g., empty data)\n if (rowCount === 0 && loadErrors.length === 0) this.emptyTables.add(tableName);\n warnings.push(`Table '${tableName}' was not loaded (no data or skipped)`);\n this.tables.delete(tableName);\n }\n } finally {\n // Remove from loading set\n loadingTables.delete(tableName);\n }\n\n return { errors, warnings, rowCounts, deferredForeignKeys };\n }\n\n /**\n * Find the schema file of a table in schemaDir, or next to the table's JSONL file when unset\n */\n private async findTableSchemaFile(tableName: string, config: TableConfig): Promise<string | undefined> {\n return findSchemaFile(this.config.schemaDir ?? dirname(config.jsonlPath), tableName);\n }\n\n /**\n * Load a single table from JSONL file\n * @returns Object with loaded status and validation errors\n */\n private async loadTable(\n tableName: string,\n config: TableConfig,\n detailedValidate: boolean,\n transform?: (row: JsonObject) => JsonObject,\n failedDependencies?: Set<string>,\n ): Promise<{ loaded: boolean; rowCount: number; errors: ValidationErrorDetail[] }> {\n // Read every JSONL file of the table, remembering where each row came from\n let data: JsonObject[] = [];\n const origins: RowOrigin[] = [];\n const contentHashes = new Map<string, string>();\n for (const jsonlPath of config.jsonlPaths ?? [config.jsonlPath]) {\n const readResult = await JsonlReader.readSnapshot(jsonlPath);\n if (!readResult.ok) {\n throw readResult.error;\n }\n const { rows, contentHash } = readResult.value;\n if (!rows.ok) {\n throw rows.error;\n }\n if (contentHash !== undefined) {\n contentHashes.set(jsonlPath, contentHash);\n this.observedHashes.set(jsonlPath, contentHash);\n }\n rows.value.forEach((row, rowIndex) => {\n data.push(row);\n origins.push({ file: jsonlPath, rowIndex });\n });\n }\n\n // Apply transform if provided (before validation)\n const transformedFields: string[][] = [];\n if (transform) {\n data = data.map((row) => {\n const transformed = transform(row);\n transformedFields.push(\n Object.keys(transformed).filter((key) => JSON.stringify(transformed[key]) !== JSON.stringify(row[key])),\n );\n return transformed;\n });\n }\n\n // Load validation schema if provided or try to auto-load\n let validationSchema = config.validationSchema;\n const schemaMetadata: {\n primaryKey?: string;\n foreignKeys?: BiDirectionalSchema['foreignKeys'];\n indexes?: BiDirectionalSchema['indexes'];\n } = {};\n\n const schemaPath = config.validationSchema ? undefined : await this.findTableSchemaFile(tableName, config);\n if (!validationSchema && schemaPath) {\n // Not loaded without validation when its schema file fails to load: rows written then would skip\n // the checks the file means to make; the error names the file and why it failed\n validationSchema = await SchemaLoader.loadSchema(config.jsonlPath, dirname(schemaPath), this.schemaImports);\n }\n\n // Load schema metadata (foreignKeys, primaryKey, indexes) from schema module\n // SchemaLoader.loadSchema() only returns the validation schema object, not metadata\n if (!config.validationSchema) {\n // Only load if not already provided via config\n try {\n if (!schemaPath) throw new Error('Schema file not found');\n const schemaModule = await this.importSchemaModule(schemaPath);\n\n // Try to get metadata from exported 'schema' or directly from module\n const schemaExport = schemaModule.schema || schemaModule.default;\n\n if (schemaExport?.primaryKey) {\n schemaMetadata.primaryKey = schemaExport.primaryKey;\n } else if (schemaModule.primaryKey) {\n schemaMetadata.primaryKey = schemaModule.primaryKey;\n }\n\n if (schemaExport?.foreignKeys) {\n schemaMetadata.foreignKeys = schemaExport.foreignKeys;\n } else if (schemaModule.foreignKeys) {\n schemaMetadata.foreignKeys = schemaModule.foreignKeys;\n }\n\n if (schemaExport?.indexes) {\n schemaMetadata.indexes = schemaExport.indexes;\n } else if (schemaModule.indexes) {\n schemaMetadata.indexes = schemaModule.indexes;\n }\n\n // Debug: log loaded metadata\n if (process.env.DEBUG_LINES_DB) {\n console.log(`[lines-db] Schema metadata for ${tableName}:`);\n console.log(` primaryKey: ${schemaMetadata.primaryKey}`);\n console.log(` foreignKeys: ${JSON.stringify(schemaMetadata.foreignKeys)}`);\n console.log(` indexes: ${JSON.stringify(schemaMetadata.indexes)}`);\n }\n } catch (_error) {\n // Schema file not found - this is OK\n // Debug: log error for investigation\n if (process.env.DEBUG_LINES_DB) {\n console.warn(\n `[lines-db] Failed to load schema metadata for ${tableName}:`,\n _error instanceof Error ? _error.message : String(_error),\n );\n }\n }\n }\n\n this.validationSchemas.set(tableName, validationSchema);\n\n // Validate data first and collect validated (transformed) data\n const validationErrors: Array<{\n rowIndex: number;\n rowData: JsonObject;\n error: ValidationError;\n }> = [];\n const validatedData: JsonObject[] = [];\n // The field order describes the rows this load computes, so a reload does not keep the order a\n // schema had the last time the table was loaded\n this.keyOrders.delete(tableName);\n\n for (let rowIndex = 0; rowIndex < data.length; rowIndex++) {\n const row = data[rowIndex];\n try {\n const validatedRow = this.validateAndTransform(tableName, row);\n this.recordKeyOrder(tableName, validatedRow);\n validatedData.push(validatedRow);\n } catch (error) {\n if (error instanceof Error && error.name === 'ValidationError') {\n validationErrors.push({\n rowIndex,\n rowData: row,\n error: error as ValidationError,\n });\n } else {\n throw error;\n }\n }\n }\n\n // Convert validation errors to ValidationErrorDetail format\n const validationErrorDetails: ValidationErrorDetail[] = validationErrors.map((ve) => ({\n ...origins[ve.rowIndex],\n tableName,\n issues: ve.error.issues,\n type: 'schema' as const,\n }));\n\n if (validationErrors.length > 0) {\n // Return errors instead of throwing\n return { loaded: false, rowCount: data.length, errors: validationErrorDetails };\n }\n\n // Determine schema - infer from validated data if auto-inference is enabled\n let schema: TableSchema;\n let inferredSchema: TableSchema | undefined;\n\n // Always infer schema from validated data to capture valueType information (e.g., boolean)\n if (validatedData.length > 0) {\n inferredSchema = unwrap(JsonlReader.inferSchema(tableName, validatedData));\n }\n\n if (config.schema) {\n schema = config.schema;\n // Merge valueType information from inferred schema\n if (inferredSchema) {\n for (const inferredCol of inferredSchema.columns) {\n const schemaCol = schema.columns.find((c) => c.name === inferredCol.name);\n if (schemaCol && inferredCol.valueType && !schemaCol.valueType) {\n schemaCol.valueType = inferredCol.valueType;\n }\n }\n }\n } else if (config.autoInferSchema !== false) {\n if (validatedData.length === 0) {\n const declared = await this.config.schemaOfEmptyTable?.({ tableName, schemaPath });\n if (!declared || declared.columns.length === 0) return { loaded: false, rowCount: 0, errors: [] };\n schema = { ...declared, name: tableName, columns: declared.columns.map((column) => ({ ...column })) };\n this.tablesFromGivenColumns.add(tableName);\n } else {\n schema = inferredSchema!;\n }\n } else {\n // Critical error - throw exception\n throw new Error(`No schema provided for table ${tableName} and autoInferSchema is disabled`);\n }\n\n // Enhance schema with constraints from validation schema and schema metadata\n // Priority: config.validationSchema (as BiDirectionalSchema) > schemaMetadata\n const biSchema = validationSchema as BiDirectionalSchema;\n const primaryKey = biSchema?.primaryKey || schemaMetadata.primaryKey;\n const foreignKeys = biSchema?.foreignKeys || schemaMetadata.foreignKeys;\n const indexes = biSchema?.indexes || schemaMetadata.indexes;\n\n if (primaryKey && !schema.columns.some((col) => col.primaryKey)) {\n // Add primary key constraint to column\n const col = schema.columns.find((c) => c.name === primaryKey);\n if (col) {\n col.primaryKey = true;\n }\n } else if (!primaryKey && !schema.columns.some((col) => col.primaryKey)) {\n // If no primary key is defined, use 'id' column as primary key if it exists\n // This matches the behavior of JsonlReader.inferSchema()\n const idColumn = schema.columns.find((c) => c.name === 'id');\n if (idColumn) {\n idColumn.primaryKey = true;\n }\n }\n if (foreignKeys) {\n schema.declaredForeignKeys = foreignKeys;\n schema.foreignKeys =\n failedDependencies && failedDependencies.size > 0\n ? foreignKeys.filter((fk) => !failedDependencies.has(fk.references.table))\n : foreignKeys;\n }\n if (indexes) {\n schema.indexes = indexes;\n\n // Apply unique constraint from single-column unique indexes to column definitions\n // This is required for foreign key references, as SQLite requires the referenced column\n // to have a UNIQUE constraint in the table definition (not just an index)\n for (const index of indexes) {\n if (index.unique && index.columns.length === 1) {\n const col = schema.columns.find((c) => c.name === index.columns[0]);\n if (col && !col.unique && !col.primaryKey) {\n col.unique = true;\n }\n }\n }\n }\n\n if (schema === inferredSchema) {\n this.relaxColumnsTheSchemaLeavesOptional(tableName, schema, data[0]);\n }\n\n this.schemas.set(tableName, schema);\n\n // Create table\n this.createTable(schema);\n\n // Insert validated data (with detailed validation if requested)\n if (detailedValidate || this.config.writeDataSets) {\n const insertErrors = this.insertDataWithDetailedValidation(tableName, schema, validatedData, origins);\n if (insertErrors.length > 0) {\n return { loaded: false, rowCount: data.length, errors: insertErrors };\n }\n } else {\n this.insertData(tableName, schema, validatedData);\n }\n\n this.fieldChanges.delete(tableName);\n this.linesWithUnknownFields.delete(tableName);\n const columnNames = new Set(schema.columns.map((column) => column.name));\n const withUnknown = data.map((row) => Object.keys(row).some((key) => !columnNames.has(key)));\n if (transformedFields.some((fields) => fields.length > 0) || withUnknown.includes(true)) {\n const rowids = this.queryInternal<JsonObject>(\n `SELECT rowid AS \"${ROWID_ALIAS}\" FROM ${this.quoteTableName(tableName)} ORDER BY rowid`,\n );\n const lines = new Map<string, JsonObject>();\n const sourceIndexes = new Map(origins.map((origin, index) => [origin, index]));\n rowids.forEach((row, index) => {\n const rowid = row[ROWID_ALIAS] as number | bigint;\n const origin = this.rowOriginsByRowid.get(tableName)?.get(String(rowid));\n const sourceIndex = origin ? (sourceIndexes.get(origin) ?? index) : index;\n const set = transformedFields[sourceIndex] ?? [];\n if (set.length > 0) this.noteFieldChanges(tableName, rowid, { set });\n if (withUnknown[sourceIndex]) lines.set(String(rowid), data[sourceIndex]);\n });\n this.linesWithUnknownFields.set(tableName, lines);\n }\n\n for (const [jsonlPath, contentHash] of contentHashes) {\n this.fileHashes.set(jsonlPath, contentHash);\n }\n return { loaded: true, rowCount: data.length, errors: [] };\n }\n\n /**\n * A column no row holds a value in has no type to read a boolean or an object back with, and so reads\n * back as 1 or as JSON text. The first value written settles it, and a string settles it as text so an\n * object written later does not turn that text into JSON. Not asked of the schema: it names no type at\n * run time. Returns what puts the columns back, which a write that did not go in, or a transaction that\n * rolled back, must call: the value that settled it is not in the table\n */\n private settleColumnsNoRowHolds(schema: TableSchema | undefined, written: JsonObject): () => void {\n const before: Array<[ColumnDefinition, ColumnDefinition['type'], ColumnDefinition['valueType']]> = [];\n for (const column of schema?.columns ?? []) {\n const value = written[column.name];\n if (column.type !== 'NULL' || value === null || value === undefined) continue;\n before.push([column, column.type, column.valueType]);\n if (typeof value === 'boolean') {\n column.type = 'INTEGER';\n column.valueType = 'boolean';\n } else if (typeof value === 'string') {\n column.type = 'TEXT';\n } else if (typeof value === 'number') {\n column.type = Number.isInteger(value) ? 'INTEGER' : 'REAL';\n } else if (typeof value === 'object' && !(value instanceof Uint8Array)) {\n column.type = 'JSON';\n } else {\n before.pop();\n }\n }\n const undo = () => {\n for (const [column, type, valueType] of before) {\n column.type = type;\n column.valueType = valueType;\n }\n };\n this.settleUndos?.push(undo);\n return undo;\n }\n\n /**\n * A column every row holds is inferred NOT NULL, which refuses a later row that leaves it out even\n * where the schema takes that row. The sample row without the field says whether the schema does.\n * A column the schema fills in stays NOT NULL: the row is stored as the schema leaves it\n */\n private relaxColumnsTheSchemaLeavesOptional(tableName: string, schema: TableSchema, sample: JsonObject | undefined) {\n if (!sample || !this.validationSchemas.get(tableName)) return;\n for (const column of schema.columns) {\n if (!column.notNull || column.primaryKey || !(column.name in sample)) continue;\n const { [column.name]: _left, ...without } = sample;\n try {\n if ((this.validateAndTransform(tableName, without)[column.name] ?? null) === null) {\n column.notNull = false;\n }\n } catch {\n // Not rethrown: a validator written for whole rows may throw on one without the field, which is no reason to fail the load\n }\n }\n }\n\n /**\n * Create table in SQLite with constraints and indexes\n */\n private createTable(schema: TableSchema): void {\n // Note: Foreign key constraints are enabled at database connection level (see sqlite-adapter.ts)\n // No need to enable them here for each table\n\n // Quote table name to handle special characters\n const quotedTableName = this.quoteTableName(schema.name);\n\n // Build a set of columns that should have UNIQUE constraint\n // This includes columns marked as unique in schema AND single-column unique indexes\n // The latter is required for foreign key references, as SQLite requires the referenced column\n // to have a UNIQUE constraint in the table definition (not just a separately created index)\n const uniqueColumns = new Set<string>();\n for (const col of schema.columns) {\n if (col.unique) {\n uniqueColumns.add(col.name);\n }\n }\n if (schema.indexes) {\n for (const index of schema.indexes) {\n if (index.unique && index.columns.length === 1) {\n uniqueColumns.add(index.columns[0]);\n }\n }\n }\n\n const columnDefs = schema.columns.map((col) => {\n // JSON type is stored as TEXT in SQLite\n const sqlType = col.type === 'JSON' ? 'TEXT' : col.type;\n const parts = [this.quoteIdentifier(col.name), sqlType];\n if (col.primaryKey) parts.push('PRIMARY KEY');\n if (col.notNull) parts.push('NOT NULL');\n if (uniqueColumns.has(col.name) && !col.primaryKey) parts.push('UNIQUE');\n return parts.join(' ');\n });\n\n // Add foreign key constraints\n const foreignKeyDefs: string[] = [];\n if (schema.foreignKeys && schema.foreignKeys.length > 0) {\n for (const fk of schema.foreignKeys) {\n const fkParts = [\n `FOREIGN KEY (${this.quoteIdentifier(fk.column)})`,\n `REFERENCES ${this.quoteTableName(fk.references.table)}(${this.quoteIdentifier(fk.references.column)})`,\n ];\n if (fk.onDelete) {\n fkParts.push(`ON DELETE ${fk.onDelete}`);\n }\n if (fk.onUpdate) {\n fkParts.push(`ON UPDATE ${fk.onUpdate}`);\n }\n foreignKeyDefs.push(fkParts.join(' '));\n }\n }\n\n const allDefs = [...columnDefs, ...foreignKeyDefs];\n const sql = `CREATE TABLE IF NOT EXISTS ${quotedTableName} (${allDefs.join(', ')})`;\n this.db.exec(sql);\n if (this.hasSeveralDataDirs() && this.config.writeDataSets) {\n const moves = this.quoteIdentifier(this.rowMovesTable);\n const trigger = this.quoteIdentifier(`${this.rowMovesTable}_${schema.name}`);\n const name = `'${schema.name.replace(/'/g, \"''\")}'`;\n this.db.exec(`CREATE TEMP TABLE IF NOT EXISTS ${moves} (tableName TEXT, oldRowid INTEGER, newRowid INTEGER)`);\n this.db.exec(`CREATE TEMP TRIGGER IF NOT EXISTS ${trigger} AFTER UPDATE ON ${quotedTableName}\n WHEN OLD.rowid != NEW.rowid BEGIN\n INSERT INTO ${moves} VALUES (${name}, OLD.rowid, NEW.rowid);\n END`);\n }\n\n // Create indexes\n if (schema.indexes && schema.indexes.length > 0) {\n for (let i = 0; i < schema.indexes.length; i++) {\n const index = schema.indexes[i];\n // Create safe index name by replacing special characters\n const safeTableName = schema.name.replace(/[^a-zA-Z0-9]/g, '_');\n const resolvedIndexName = index.name || `idx_${safeTableName}_${index.columns.join('_')}_${i}`;\n const uniqueKeyword = index.unique ? 'UNIQUE ' : '';\n const indexSql = `CREATE ${uniqueKeyword}INDEX IF NOT EXISTS ${this.quoteIdentifier(resolvedIndexName)} ON ${quotedTableName} (${index.columns\n .map((col) => this.quoteIdentifier(col))\n .join(', ')})`;\n this.db.exec(indexSql);\n }\n }\n }\n\n /**\n * Quote table name to handle special characters in SQL\n */\n private quoteTableName(tableName: string): string {\n return this.quoteIdentifier(tableName);\n }\n\n /**\n * Quote identifier for SQL statements, escaping embedded quotes\n */\n private quoteIdentifier(identifier: string): string {\n return `\"${identifier.replace(/\"/g, '\"\"')}\"`;\n }\n\n /**\n * Insert data into table using batch insert (multiple rows per SQL)\n * SQLite has a parameter limit (default 999), so we batch rows accordingly\n * Throws exception if any constraint violation occurs\n */\n private insertData(tableName: string, schema: TableSchema, data: JsonObject[]): void {\n if (data.length === 0) return;\n\n const columnNames = schema.columns.map((col) => col.name);\n const quotedColumns = columnNames.map((name) => this.quoteIdentifier(name));\n const columnsByName = new Map(schema.columns.map((column) => [column.name, column]));\n const columnCount = columnNames.length;\n\n // Calculate batch size to stay under SQLite's parameter limit (999)\n // Leave some margin for safety\n const maxBatchSize = Math.floor(900 / columnCount);\n const batchSize = Math.max(1, Math.min(maxBatchSize, 100));\n\n // Process data in batches\n for (let i = 0; i < data.length; i += batchSize) {\n const batch = data.slice(i, i + batchSize);\n const rowPlaceholders = columnNames.map(() => '?').join(', ');\n const valuesPlaceholders = batch.map(() => `(${rowPlaceholders})`).join(', ');\n const sql = `INSERT INTO ${this.quoteTableName(tableName)} (${quotedColumns.join(', ')}) VALUES ${valuesPlaceholders}`;\n\n const values: (string | number | bigint | null | Uint8Array)[] = [];\n for (const row of batch) {\n for (const col of columnNames) {\n values.push(this.normalizeValue(row[col], columnsByName.get(col)));\n }\n }\n\n const stmt = this.db.prepare(sql);\n stmt.run(...values);\n }\n }\n\n /**\n * Insert data into table one row at a time with detailed error reporting\n * This is used for validation to catch constraint violations\n */\n private insertDataWithDetailedValidation(\n tableName: string,\n schema: TableSchema,\n data: JsonObject[],\n origins: RowOrigin[],\n ): ValidationErrorDetail[] {\n const errors: ValidationErrorDetail[] = [];\n const columnNames = schema.columns.map((col) => col.name);\n const quotedColumns = columnNames.map((name) => this.quoteIdentifier(name));\n const placeholders = columnNames.map(() => '?').join(', ');\n const sql = `INSERT INTO ${this.quoteTableName(tableName)} (${quotedColumns.join(', ')}) VALUES (${placeholders})`;\n const columnsByName = new Map(schema.columns.map((column) => [column.name, column]));\n\n const stmt = this.db.prepare(sql);\n const rowOrigins = new Map<string, RowOrigin>();\n this.rowOriginsByRowid.set(tableName, rowOrigins);\n\n for (let rowIndex = 0; rowIndex < data.length; rowIndex++) {\n const row = data[rowIndex];\n try {\n const values = columnNames.map((col) => this.normalizeValue(row[col], columnsByName.get(col)));\n const { lastInsertRowid } = stmt.run(...values);\n rowOrigins.set(String(lastInsertRowid), origins[rowIndex]);\n } catch (error) {\n // Constraint violation occurred - analyze and record details\n const constraintError = this.analyzeConstraintError(\n error,\n origins[rowIndex].file,\n tableName,\n origins[rowIndex].rowIndex,\n row,\n schema.foreignKeys || [],\n );\n if (constraintError) {\n errors.push(constraintError);\n }\n }\n }\n\n return errors;\n }\n\n /**\n * Analyze constraint error and extract detailed information\n */\n private analyzeConstraintError(\n error: unknown,\n file: string,\n tableName: string,\n rowIndex: number,\n row: JsonObject,\n foreignKeys: ForeignKeyDefinition[],\n ): ValidationErrorDetail | null {\n const errorMessage = error instanceof Error ? error.message : String(error);\n\n // Foreign key constraint\n if (errorMessage.includes('FOREIGN KEY constraint failed')) {\n // Find which foreign key failed\n for (const fk of foreignKeys) {\n const fkValue = row[fk.column];\n if (fkValue === null || fkValue === undefined) continue;\n\n // Check if referenced value exists\n try {\n const result = this.queryInternal(\n `SELECT COUNT(*) as count FROM ${this.quoteIdentifier(fk.references.table)} WHERE ${this.quoteIdentifier(fk.references.column)} = ?`,\n [this.normalizeValue(fkValue, this.columnOf(fk.references.table, fk.references.column))],\n );\n if (result.length > 0 && (result[0] as { count: number }).count === 0) {\n return {\n file,\n tableName,\n rowIndex,\n issues: [],\n type: 'foreignKey',\n foreignKeyError: {\n column: fk.column,\n value: fkValue,\n referencedTable: fk.references.table,\n referencedColumn: fk.references.column,\n },\n };\n }\n } catch (_) {\n // Referenced table doesn't exist yet\n }\n }\n }\n\n // Other constraint errors (primary key, unique, etc.)\n return {\n file,\n tableName,\n rowIndex,\n issues: [\n {\n message: errorMessage,\n path: [],\n },\n ],\n type: 'schema',\n };\n }\n\n /**\n * Validate a deferred foreign key constraint after all tables have been loaded.\n * Used for circular dependency FK validation.\n */\n private validateDeferredForeignKey(\n tableName: string,\n fk: ForeignKeyDefinition,\n filePath: string,\n ): ValidationErrorDetail[] {\n const errors: ValidationErrorDetail[] = [];\n const quotedTable = this.quoteTableName(tableName);\n const quotedColumn = this.quoteIdentifier(fk.column);\n const quotedRefTable = this.quoteTableName(fk.references.table);\n const quotedRefColumn = this.quoteIdentifier(fk.references.column);\n\n // Find rows where the FK value does not exist in the referenced table\n const sql = `SELECT rowid as rid, ${quotedColumn} as val FROM ${quotedTable} WHERE ${quotedColumn} IS NOT NULL AND ${quotedColumn} NOT IN (SELECT ${quotedRefColumn} FROM ${quotedRefTable})`;\n\n try {\n const rows = this.queryInternal<{ rid: number | bigint; val: string | number }>(sql);\n const rowOrigins = this.rowOriginsByRowid.get(tableName);\n for (const row of rows) {\n errors.push({\n ...(rowOrigins?.get(String(row.rid)) ?? { file: filePath, rowIndex: Number(row.rid) - 1 }),\n tableName,\n issues: [],\n type: 'foreignKey',\n foreignKeyError: {\n column: fk.column,\n value: row.val,\n referencedTable: fk.references.table,\n referencedColumn: fk.references.column,\n },\n });\n }\n } catch (_) {\n // Table might not exist - skip validation\n }\n\n return errors;\n }\n\n /**\n * Execute a raw SQL query\n */\n query<T = unknown>(sql: string, params: (string | number | bigint | null | Uint8Array)[] = []): Result<T[], Error> {\n try {\n this.enforceReadOnlySql();\n this.refuseUnsafeSql(sql);\n return ok(this.trackRawSql(() => this.readOnlyWhileTransactionSettles(() => this.queryInternal<T>(sql, params))));\n } catch (error) {\n return err(toError(error));\n }\n }\n\n private queryInternal<T = unknown>(sql: string, params: (string | number | bigint | null | Uint8Array)[] = []): T[] {\n const stmt = this.db.prepare(sql);\n return stmt.all(...params) as T[];\n }\n\n /**\n * Execute a SQL query that returns a single row\n */\n queryOne<T = unknown>(\n sql: string,\n params: (string | number | bigint | null | Uint8Array)[] = [],\n ): Result<T | null, Error> {\n try {\n this.enforceReadOnlySql();\n this.refuseUnsafeSql(sql);\n return ok(\n this.trackRawSql(() => this.readOnlyWhileTransactionSettles(() => this.queryOneInternal<T>(sql, params))),\n );\n } catch (error) {\n return err(toError(error));\n }\n }\n\n private queryOneInternal<T = unknown>(\n sql: string,\n params: (string | number | bigint | null | Uint8Array)[] = [],\n ): T | null {\n const stmt = this.db.prepare(sql);\n const result = stmt.get(...params);\n return result === undefined ? null : (result as T);\n }\n\n /**\n * Execute a SQL statement (INSERT, UPDATE, DELETE)\n */\n execute(\n sql: string,\n params: (string | number | bigint | null | Uint8Array)[] = [],\n ): Result<{ changes: number | bigint; lastInsertRowid: number | bigint }, Error> {\n try {\n this.enforceReadOnlySql();\n this.refuseUnsafeSql(sql);\n this.refuseWhileTransactionSettles('run SQL');\n return ok(this.trackRawSql(() => this.readOnlyWhileTransactionSettles(() => this.executeInternal(sql, params))));\n } catch (error) {\n return err(toError(error));\n }\n }\n\n /**\n * Run a caller's SQL, and when it changed rows, write back every table whole: which tables and\n * fields raw SQL changed is unknown, and a query() can change rows with RETURNING too\n */\n private trackRawSql<T>(run: () => T): T {\n const before = this.totalChanges();\n // Not only when it returns: SQL of several statements can change rows and then fail on a later one\n try {\n return run();\n } finally {\n if (this.totalChanges() !== before) {\n for (const tableName of this.schemas.keys()) {\n this.rawSqlTables.add(tableName);\n this.noteChange(tableName);\n }\n this.forgetLinesOfGoneRows(this.schemas.keys());\n if (this.transactionChanges) this.transactionChanges = 'all';\n }\n }\n }\n\n private totalChanges(): number {\n return Number((this.db.prepare('SELECT total_changes() AS n').get() as { n: number | bigint }).n);\n }\n\n private executeInternal(\n sql: string,\n params: (string | number | bigint | null | Uint8Array)[] = [],\n ): { changes: number | bigint; lastInsertRowid: number | bigint } {\n const stmt = this.db.prepare(sql);\n const result = stmt.run(...params);\n if (this.hasSeveralDataDirs() && this.config.writeDataSets) {\n const moves = this.quoteIdentifier(this.rowMovesTable);\n const changes = this.queryInternal<{ tableName: string; oldRowid: number | bigint; newRowid: number | bigint }>(\n `SELECT tableName, oldRowid, newRowid FROM ${moves} ORDER BY rowid`,\n );\n for (const change of changes)\n this.moveRowMetadata(change.tableName, String(change.oldRowid), String(change.newRowid));\n if (changes.length > 0) this.db.exec(`DELETE FROM ${moves}`);\n }\n return result;\n }\n\n /**\n * Find rows by condition (supports OR/AND with arrays and function filters)\n * If where is not provided, returns all rows\n */\n find<K extends keyof Tables & string>(tableName: K, where?: WhereCondition<Tables[K]>): Result<Tables[K][], Error> {\n try {\n return ok(this.findInternal(tableName, where));\n } catch (error) {\n return err(toError(error));\n }\n }\n\n private findInternal<K extends keyof Tables & string>(tableName: K, where?: WhereCondition<Tables[K]>): Tables[K][] {\n // If no where condition, return all rows\n if (where === undefined) {\n const rows = this.queryInternal(`SELECT * FROM ${this.quoteTableName(tableName)}`);\n return rows.map((row) => this.deserializeRow(tableName, row)) as Tables[K][];\n }\n\n // Handle empty array - should return no results\n if (Array.isArray(where) && where.length === 0) {\n return [];\n }\n\n const { sql, values, functionFilters, hasOrWithFunctionFilters } = this.buildWhereClause(where, tableName);\n\n let rows: Tables[K][];\n\n // If OR condition has function filters, get all rows and evaluate in JS\n if (hasOrWithFunctionFilters) {\n const rawRows = this.queryInternal(`SELECT * FROM ${this.quoteTableName(tableName)}`);\n rows = rawRows.map((row) => this.deserializeRow(tableName, row)) as Tables[K][];\n return this.applyOrConditionWithFilters(rows, where as WhereCondition<Tables[K]>);\n }\n\n // Normal case: use SQL WHERE clause\n if (sql) {\n const rawRows = this.queryInternal(`SELECT * FROM ${this.quoteTableName(tableName)} WHERE ${sql}`, values);\n rows = rawRows.map((row) => this.deserializeRow(tableName, row)) as Tables[K][];\n } else {\n // If only function filters (AND case), get all rows\n const rawRows = this.queryInternal(`SELECT * FROM ${this.quoteTableName(tableName)}`);\n rows = rawRows.map((row) => this.deserializeRow(tableName, row)) as Tables[K][];\n }\n\n // Apply function filters for AND conditions\n return this.applyFunctionFilters(rows, functionFilters);\n }\n\n /**\n * Find a single row by condition (supports OR/AND with arrays and function filters)\n */\n findOne<K extends keyof Tables & string>(\n tableName: K,\n where: WhereCondition<Tables[K]>,\n ): Result<Tables[K] | null, Error> {\n try {\n return ok(this.findOneInternal(tableName, where));\n } catch (error) {\n return err(toError(error));\n }\n }\n\n private findOneInternal<K extends keyof Tables & string>(\n tableName: K,\n where: WhereCondition<Tables[K]>,\n ): Tables[K] | null {\n const { sql, values, functionFilters } = this.buildWhereClause(where, tableName);\n\n let rows: Tables[K][];\n if (sql) {\n const rawRows = this.queryInternal(`SELECT * FROM ${this.quoteTableName(tableName)} WHERE ${sql}`, values);\n rows = rawRows.map((row) => this.deserializeRow(tableName, row)) as Tables[K][];\n } else {\n // If only function filters, get all rows\n const rawRows = this.queryInternal(`SELECT * FROM ${this.quoteTableName(tableName)}`);\n rows = rawRows.map((row) => this.deserializeRow(tableName, row)) as Tables[K][];\n }\n\n // Apply function filters and return first match\n const filtered = this.applyFunctionFilters(rows, functionFilters);\n return filtered.length > 0 ? filtered[0] : null;\n }\n\n /**\n * Deserialize JSON columns in a row\n */\n private deserializeRow<T>(tableName: string, row: T): T {\n const schema = this.schemas.get(tableName);\n if (!schema) return row;\n\n const deserializedRow = { ...row } as Record<string, unknown>;\n\n for (const column of schema.columns) {\n const colName = column.name;\n if (!(colName in deserializedRow)) continue;\n\n const value = deserializedRow[colName];\n\n if (column.type === 'JSON' && typeof value === 'string') {\n try {\n deserializedRow[colName] = JSON.parse(value);\n } catch (error) {\n // If parsing fails, keep the original value\n console.warn(`Failed to parse JSON column ${colName}:`, error);\n }\n continue;\n }\n\n if (column.valueType === 'boolean') {\n if (typeof value === 'number') {\n deserializedRow[colName] = value === 0 ? false : true;\n } else if (typeof value === 'bigint') {\n deserializedRow[colName] = value === 0n ? false : true;\n }\n }\n }\n\n return deserializedRow as T;\n }\n\n /**\n * Validate data using StandardSchema and return the transformed value\n * Note: Only synchronous validation is supported\n */\n private validateAndTransform(tableName: string, data: unknown): JsonObject {\n const schema = this.validationSchemas.get(tableName);\n if (!schema) {\n return data as JsonObject;\n }\n\n const result = schema['~standard'].validate(data);\n\n // Only synchronous validation is supported\n if (result instanceof Promise) {\n throw new Error('Asynchronous validation is not supported. Please use synchronous validation schemas.');\n }\n\n if (result.issues && result.issues.length > 0) {\n // Format detailed error message with all validation issues\n const issueMessages = result.issues\n .map((issue) => {\n // Handle path: can be array of PathSegment or undefined\n let pathStr = 'root';\n if (issue.path && issue.path.length > 0) {\n pathStr = issue.path\n .map((segment) => {\n // PathSegment can be { key: PropertyKey } or just PropertyKey\n if (typeof segment === 'object' && segment !== null && 'key' in segment) {\n return String(segment.key);\n }\n return String(segment);\n })\n .join('.');\n }\n return ` - ${pathStr}: ${issue.message}`;\n })\n .join('\\n');\n\n const errorMessage = `Validation failed for table '${tableName}':\\n${issueMessages}`;\n const error = new Error(errorMessage) as ValidationError;\n error.name = 'ValidationError';\n error.issues = result.issues;\n throw error;\n }\n\n // Return the transformed value from validation\n // When there are no issues, result.value should be present\n const transformedValue = ('value' in result ? result.value : data) as JsonObject;\n\n // Convert undefined values to null for JSON compatibility\n const normalizedValue: JsonObject = {};\n for (const [key, value] of Object.entries(transformedValue)) {\n normalizedValue[key] = value === undefined ? null : value;\n }\n\n return normalizedValue;\n }\n\n /**\n * Validate data using StandardSchema (without returning transformed value)\n * Note: Only synchronous validation is supported\n */\n private validateData(tableName: string, data: unknown): void {\n // Use validateAndTransform but discard the result\n this.validateAndTransform(tableName, data);\n }\n\n /**\n * Remember the order a computed row lists its fields in - the order the schema declares them, since\n * that is the order a hook or a validation fills a row in. A sync inserts a key the line did not\n * have at the place this order gives it.\n */\n private recordKeyOrder(tableName: string, row: JsonObject): void {\n const order = this.keyOrders.get(tableName) ?? new Set<string>();\n for (const key of Object.keys(row)) {\n // A set keeps the order keys were added in, so a field only some rows carry lands after the\n // ones already seen - which is where the row that carries it puts it too\n order.add(key);\n }\n this.keyOrders.set(tableName, order);\n }\n\n /**\n * Insert a row into a table with validation\n */\n insert<K extends keyof Tables & string>(\n tableName: K,\n data: Tables[K],\n options?: { dataDir?: string },\n ): Result<{ changes: number | bigint; lastInsertRowid: number | bigint }, Error> {\n try {\n return ok(this.insertInternal(tableName, data, options));\n } catch (error) {\n return err(toError(error));\n }\n }\n\n private insertInternal<K extends keyof Tables & string>(\n tableName: K,\n data: Tables[K],\n options?: { dataDir?: string },\n ): { changes: number | bigint; lastInsertRowid: number | bigint } {\n this.assertMutable(tableName);\n let destination: string | undefined;\n if (this.hasSeveralDataDirs()) {\n const dataDir = options?.dataDir;\n if (!dataDir || ![this.config.dataDir].flat().some((dir) => resolve(dir) === resolve(dataDir))) {\n throw new Error('Choose an insert dataDir from the configured data directories');\n }\n destination = join(\n [this.config.dataDir].flat().find((dir) => resolve(dir) === resolve(dataDir))!,\n `${tableName}.jsonl`,\n );\n }\n\n // Not inserting the row as given: a value the schema fills in would be missing, unlike in a loaded row\n const row = this.validateAndTransform(tableName, data);\n\n const schema = this.schemas.get(tableName);\n if (!schema) {\n throw new Error(`Table ${tableName} does not exist`);\n }\n\n this.addMissingColumns(tableName, schema, row);\n\n const columnNames = Object.keys(row);\n const quotedColumns = columnNames.map((col) => this.quoteIdentifier(col));\n const placeholders = columnNames.map(() => '?').join(', ');\n const sql = `INSERT INTO ${this.quoteTableName(tableName)} (${quotedColumns.join(', ')}) VALUES (${placeholders})`;\n\n const values = columnNames.map((col) => this.normalizeValue(row[col], this.columnOf(tableName, col)));\n // After the values: one the database cannot take throws there, with nothing to undo yet\n const undoSettle = this.settleColumnsNoRowHolds(schema, row);\n let result: ReturnType<typeof this.executeInternal>;\n try {\n result = this.executeInternal(sql, values);\n } catch (error) {\n undoSettle();\n throw error;\n }\n if (destination) {\n const origins = this.rowOriginsByRowid.get(tableName) ?? new Map<string, RowOrigin>();\n origins.set(String(result.lastInsertRowid), { file: destination, rowIndex: -1 });\n this.rowOriginsByRowid.set(tableName, origins);\n }\n this.noteFieldChanges(tableName, result.lastInsertRowid, { set: givenFields(data), inserted: true });\n\n // Auto-sync if not in transaction\n this.afterWrite(tableName, result.changes);\n\n return result;\n }\n\n /**\n * A table made from the columns given has only those, and the validator may add a field they lack: the\n * columns of a table made from rows are those of the validated rows, which have it\n */\n private addMissingColumns(tableName: string, schema: TableSchema, row: JsonObject): void {\n if (!this.tablesFromGivenColumns.has(tableName)) return;\n const known = new Set(schema.columns.map((column) => column.name));\n const missing = Object.keys(row).filter((key) => !known.has(key));\n if (missing.length === 0) return;\n for (const column of unwrap(JsonlReader.inferSchema(tableName, [row])).columns) {\n if (!missing.includes(column.name)) continue;\n const sqlType = column.type === 'JSON' ? 'TEXT' : column.type;\n this.db.exec(\n `ALTER TABLE ${this.quoteTableName(tableName)} ADD COLUMN ${this.quoteIdentifier(column.name)} ${sqlType}`,\n );\n schema.columns.push({ name: column.name, type: column.type, notNull: false, valueType: column.valueType });\n }\n }\n\n /**\n * Batch insert rows with validation per record.\n */\n batchInsert<K extends keyof Tables & string>(\n tableName: K,\n records: Tables[K][],\n ): Result<{ changes: number | bigint; lastInsertRowid: number | bigint }, Error> {\n try {\n return ok(this.batchInsertInternal(tableName, records));\n } catch (error) {\n return err(toError(error));\n }\n }\n\n private batchInsertInternal<K extends keyof Tables & string>(\n tableName: K,\n records: Tables[K][],\n ): { changes: number | bigint; lastInsertRowid: number | bigint } {\n this.assertMutable(tableName);\n if (this.hasSeveralDataDirs()) throw new Error('Use insert with a dataDir for data sets');\n\n const schema = this.schemas.get(tableName);\n if (!schema) {\n throw new Error(`Table ${tableName} does not exist`);\n }\n\n if (records.length === 0) {\n return { changes: 0, lastInsertRowid: 0 };\n }\n\n let totalChanges = 0n;\n let lastRowid = 0n;\n\n // Not only once every record went in: the caller may go on after a failed one, keeping those before it\n try {\n for (const record of records) {\n const row = this.validateAndTransform(tableName, record);\n this.addMissingColumns(tableName, schema, row);\n\n const columnNames = Object.keys(row);\n const quotedColumns = columnNames.map((col) => this.quoteIdentifier(col));\n const placeholders = columnNames.map(() => '?').join(', ');\n const sql = `INSERT INTO ${this.quoteTableName(tableName)} (${quotedColumns.join(', ')}) VALUES (${placeholders})`;\n\n const values = columnNames.map((col) => this.normalizeValue(row[col], this.columnOf(tableName, col)));\n const undoSettle = this.settleColumnsNoRowHolds(this.schemas.get(tableName), row);\n\n let result: ReturnType<typeof this.executeInternal>;\n try {\n result = this.executeInternal(sql, values);\n } catch (error) {\n undoSettle();\n throw error;\n }\n this.noteFieldChanges(tableName, result.lastInsertRowid, { set: givenFields(record), inserted: true });\n totalChanges += BigInt(result.changes);\n lastRowid = BigInt(result.lastInsertRowid);\n }\n } finally {\n this.afterWrite(tableName, totalChanges);\n }\n\n return {\n changes: totalChanges,\n lastInsertRowid: lastRowid,\n };\n }\n\n /**\n * Update rows in a table with validation (supports OR/AND with arrays)\n * Note: Function filters are not supported for update operations\n * Note: By default, validation is enabled. For partial updates, existing data is fetched\n * and merged before validation. Set options.validate = false to disable validation.\n */\n update<K extends keyof Tables & string>(\n tableName: K,\n data: Partial<Tables[K]>,\n where: WhereCondition<Tables[K]>,\n options?: UpdateOptions,\n ): Result<{ changes: number | bigint; lastInsertRowid: number | bigint }, Error> {\n try {\n return ok(this.updateInternal(tableName, data, where, options));\n } catch (error) {\n return err(toError(error));\n }\n }\n\n private updateInternal<K extends keyof Tables & string>(\n tableName: K,\n data: Partial<Tables[K]>,\n where: WhereCondition<Tables[K]>,\n options?: UpdateOptions,\n ): { changes: number | bigint; lastInsertRowid: number | bigint } {\n this.assertMutable(tableName);\n\n const schema = this.schemas.get(tableName);\n if (!schema) {\n throw new Error(`Table ${tableName} does not exist`);\n }\n\n // Validate by default (can be disabled with validate: false)\n const shouldValidate = options?.validate !== false;\n const hasValidationSchema = this.validationSchemas.has(tableName);\n\n if (shouldValidate && hasValidationSchema) {\n // Get existing rows to merge with partial data\n const existingRows = this.findInternal(tableName, where);\n\n // Validate each merged row\n for (const existingRow of existingRows) {\n const mergedData: Record<string, unknown> = { ...existingRow, ...data };\n // Not checked with the values the update resets: they are about to be replaced by the schema's\n for (const field of options?.resetToDefault ?? []) delete mergedData[field];\n this.validateData(tableName, mergedData);\n }\n }\n\n const { sql: whereSql, values: whereValues, functionFilters } = this.buildWhereClause(where, tableName);\n\n if (functionFilters.length > 0) {\n throw new Error('Function filters are not supported in update operations');\n }\n\n const targets = this.queryInternal<JsonObject>(\n `SELECT rowid AS \"${ROWID_ALIAS}\", * FROM ${this.quoteTableName(tableName)} WHERE ${whereSql}`,\n whereValues,\n );\n\n // Not computed after the UPDATE: a reset the schema refuses must fail the update before it changes anything\n const resetFields = options?.resetToDefault ?? [];\n const resets =\n resetFields.length > 0 ? this.computeResets(tableName, targets, data as JsonObject, resetFields) : [];\n\n let result: { changes: number | bigint; lastInsertRowid: number | bigint } = { changes: 0, lastInsertRowid: 0 };\n if (Object.keys(data).length > 0) {\n const setClauses = Object.keys(data)\n .map((key) => `${this.quoteIdentifier(key)} = ?`)\n .join(', ');\n const sql = `UPDATE ${this.quoteTableName(tableName)} SET ${setClauses} WHERE ${whereSql}`;\n const values = [\n ...Object.entries(data).map(([key, v]) => this.normalizeValue(v, this.columnOf(tableName, key))),\n ...whereValues,\n ];\n const undoSettle = this.settleColumnsNoRowHolds(this.schemas.get(tableName), data as JsonObject);\n try {\n result = this.executeInternal(sql, values);\n } catch (error) {\n undoSettle();\n throw error;\n }\n if (Number(result.changes) === 0) undoSettle();\n }\n\n const pkName = this.schemas.get(tableName)?.columns.find((col) => col.primaryKey)?.name;\n if (pkName && Object.hasOwn(data, pkName)) {\n // An INTEGER PRIMARY KEY is the rowid, so a new key moves the row, and what is kept by rowid with it\n const moved = this.queryInternal<JsonObject>(\n `SELECT rowid AS \"${ROWID_ALIAS}\" FROM ${this.quoteTableName(tableName)} WHERE ${this.quoteIdentifier(pkName)} = ?`,\n [this.normalizeValue((data as Record<string, unknown>)[pkName], this.columnOf(tableName, pkName))],\n );\n if (targets.length === 1 && moved.length === 1) {\n const from = String(targets[0][ROWID_ALIAS]);\n const to = moved[0][ROWID_ALIAS];\n if (from !== String(to)) {\n this.moveRowMetadata(tableName, from, String(to));\n targets[0] = { ...targets[0], [ROWID_ALIAS]: to };\n }\n }\n }\n\n for (const target of targets) {\n const set = Object.keys(data).filter(\n (key) =>\n !sameStoredValue(\n target[key],\n this.normalizeValue((data as Record<string, unknown>)[key], this.columnOf(tableName, key)),\n ),\n );\n this.noteFieldChanges(tableName, target[ROWID_ALIAS] as number | bigint, { set });\n }\n\n if (resets.length > 0) {\n result = this.applyResets(tableName, resets, resetFields);\n }\n\n // Auto-sync if not in transaction\n this.afterWrite(tableName, result.changes);\n\n return result;\n }\n\n /**\n * Batch update rows with record-specific values and validation.\n * Each record must include the primary key to identify the target row.\n * Validation runs once per merged record unless explicitly disabled.\n */\n batchUpdate<K extends keyof Tables & string>(\n tableName: K,\n records: Array<Partial<Tables[K]> & Record<string, unknown>>,\n options?: { validate?: boolean },\n ): Result<{ changes: number | bigint; lastInsertRowid: number | bigint }, Error> {\n try {\n return ok(this.batchUpdateInternal(tableName, records, options));\n } catch (error) {\n return err(toError(error));\n }\n }\n\n private batchUpdateInternal<K extends keyof Tables & string>(\n tableName: K,\n records: Array<Partial<Tables[K]> & Record<string, unknown>>,\n options?: { validate?: boolean },\n ): { changes: number | bigint; lastInsertRowid: number | bigint } {\n this.assertMutable(tableName);\n\n const schema = this.schemas.get(tableName);\n if (!schema) {\n throw new Error(`Table ${tableName} does not exist`);\n }\n\n if (records.length === 0) {\n return { changes: 0, lastInsertRowid: 0 };\n }\n\n // Get primary key column\n const pkColumn = schema.columns.find((col) => col.primaryKey);\n if (!pkColumn) {\n throw new Error(`Table ${tableName} does not have a primary key`);\n }\n\n const pkName = pkColumn.name;\n\n // Extract primary key values from records\n const pkValues: unknown[] = [];\n for (const record of records) {\n const pkValue = record[pkName];\n if (pkValue === undefined) {\n throw new Error(`Record is missing primary key '${String(pkName)}': ${JSON.stringify(record)}`);\n }\n pkValues.push(pkValue);\n }\n\n // Validate by default (can be disabled with validate: false)\n const shouldValidate = options?.validate !== false;\n const hasValidationSchema = this.validationSchemas.has(tableName);\n\n if (shouldValidate && hasValidationSchema) {\n // Build OR condition to fetch all existing rows at once\n const orCondition = pkValues.map((pkValue) => ({\n [pkName]: pkValue,\n })) as WhereCondition<Tables[K]>;\n\n // Fetch all existing rows in one query\n const existingRows = this.findInternal(tableName, orCondition);\n\n // Create a map for fast lookup: pkValue -> existingRow\n const existingRowsMap = new Map<unknown, Tables[K]>();\n for (const row of existingRows) {\n const pkValue = (row as Record<string, unknown>)[pkName];\n existingRowsMap.set(pkValue, row);\n }\n\n // Validate each merged record and collect all errors\n const validationErrors: Array<{\n rowIndex: number;\n rowData: unknown;\n pkValue: unknown;\n error: ValidationError;\n }> = [];\n\n for (let i = 0; i < records.length; i++) {\n const record = records[i];\n const pkValue = record[pkName];\n const existingRow = existingRowsMap.get(pkValue);\n\n if (!existingRow) {\n throw new Error(`No existing row found with ${String(pkName)}=${JSON.stringify(pkValue)}`);\n }\n\n const mergedData = { ...existingRow, ...record };\n\n try {\n this.validateData(tableName, mergedData);\n } catch (error) {\n // Collect validation errors instead of throwing immediately\n if (error instanceof Error && error.name === 'ValidationError') {\n validationErrors.push({\n rowIndex: i,\n rowData: mergedData,\n pkValue,\n error: error as ValidationError,\n });\n } else {\n throw error;\n }\n }\n }\n\n // If there are validation errors, throw with all error information\n if (validationErrors.length > 0) {\n const enhancedError = new Error(\n `Validation failed for ${validationErrors.length} row(s)`,\n ) as ValidationError & { validationErrors: typeof validationErrors };\n enhancedError.name = 'ValidationError';\n enhancedError.validationErrors = validationErrors;\n // For backward compatibility, include issues from first error\n enhancedError.issues = validationErrors[0].error.issues;\n throw enhancedError;\n }\n }\n\n // All validations passed - perform updates\n let totalChanges = 0n;\n let lastRowid = 0n;\n\n for (const record of records) {\n const pkValue = record[pkName];\n const where = { [pkName]: pkValue } as WhereCondition<Tables[K]>;\n\n // Call update without validation (already validated above)\n const result = this.updateInternal(tableName, record as Partial<Tables[K]>, where, {\n validate: false,\n });\n\n totalChanges += BigInt(result.changes);\n lastRowid = BigInt(result.lastInsertRowid);\n }\n\n return {\n changes: totalChanges,\n lastInsertRowid: lastRowid,\n };\n }\n\n /**\n * Delete rows from a table (supports OR/AND with arrays)\n * Note: Function filters are not supported for delete operations\n */\n delete<K extends keyof Tables & string>(\n tableName: K,\n where: WhereCondition<Tables[K]>,\n ): Result<{ changes: number | bigint; lastInsertRowid: number | bigint }, Error> {\n try {\n return ok(this.deleteInternal(tableName, where));\n } catch (error) {\n return err(toError(error));\n }\n }\n\n private deleteInternal<K extends keyof Tables & string>(\n tableName: K,\n where: WhereCondition<Tables[K]>,\n ): { changes: number | bigint; lastInsertRowid: number | bigint } {\n this.assertMutable(tableName);\n\n const schema = this.schemas.get(tableName);\n if (!schema) {\n throw new Error(`Table ${tableName} does not exist`);\n }\n\n const { sql: whereSql, values, functionFilters } = this.buildWhereClause(where, tableName);\n\n if (functionFilters.length > 0) {\n throw new Error('Function filters are not supported in delete operations');\n }\n\n const deleted = this.rowidsWhere(tableName, whereSql, values);\n const sql = `DELETE FROM ${this.quoteTableName(tableName)} WHERE ${whereSql}`;\n const result = this.executeInternal(sql, values);\n this.forgetFieldChanges(tableName, deleted);\n\n // Auto-sync if not in transaction\n this.afterWrite(tableName, result.changes);\n\n return result;\n }\n\n /**\n * Batch delete rows by primary key.\n */\n batchDelete<K extends keyof Tables & string>(\n tableName: K,\n records: Array<Partial<Tables[K]> & Record<string, unknown>>,\n ): Result<{ changes: number | bigint; lastInsertRowid: number | bigint }, Error> {\n try {\n return ok(this.batchDeleteInternal(tableName, records));\n } catch (error) {\n return err(toError(error));\n }\n }\n\n private batchDeleteInternal<K extends keyof Tables & string>(\n tableName: K,\n records: Array<Partial<Tables[K]> & Record<string, unknown>>,\n ): { changes: number | bigint; lastInsertRowid: number | bigint } {\n this.assertMutable(tableName);\n\n const schema = this.schemas.get(tableName);\n if (!schema) {\n throw new Error(`Table ${tableName} does not exist`);\n }\n\n if (records.length === 0) {\n return { changes: 0, lastInsertRowid: 0 };\n }\n\n const pkColumn = schema.columns.find((col) => col.primaryKey);\n if (!pkColumn) {\n throw new Error(`Table ${tableName} does not have a primary key`);\n }\n const pkName = pkColumn.name;\n\n const pkValues = records.map((record, index) => {\n const pkValue = record[pkName as keyof Tables[K]];\n if (pkValue === undefined) {\n throw new Error(`Record at index ${index} is missing primary key '${String(pkName)}'`);\n }\n return pkValue;\n });\n\n const placeholders = pkValues.map(() => '?').join(', ');\n const sql = `DELETE FROM ${this.quoteTableName(tableName)} WHERE ${this.quoteIdentifier(pkName)} IN (${placeholders})`;\n const values = pkValues.map((value) => this.normalizeValue(value, this.columnOf(tableName, pkName)));\n const deleted = this.rowidsWhere(tableName, `${this.quoteIdentifier(pkName)} IN (${placeholders})`, values);\n const result = this.executeInternal(sql, values);\n this.forgetFieldChanges(tableName, deleted);\n\n this.afterWrite(tableName, result.changes);\n\n return {\n changes: BigInt(result.changes),\n lastInsertRowid: BigInt(result.lastInsertRowid),\n };\n }\n\n /**\n * Normalize value for SQLite\n */\n private normalizeValue(value: unknown, column?: { type: string }): string | number | bigint | null | Uint8Array {\n if (value === null || value === undefined) return null;\n // A JSON column holds JSON text for every value, a string quoted, so that reading it back with JSON.parse gives the type it had\n if (column?.type === 'JSON') {\n if (value instanceof Uint8Array) return value;\n return typeof value === 'bigint' ? value.toString() : JSON.stringify(value);\n }\n if (typeof value === 'boolean') return value ? 1 : 0;\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'bigint') return value;\n if (value instanceof Uint8Array) return value;\n // For objects, convert to JSON string\n return JSON.stringify(value);\n }\n\n private columnOf(tableName: string, columnName: string): { type: string } | undefined {\n return this.schemas.get(tableName)?.columns.find((column) => column.name === columnName);\n }\n\n /**\n * Build WHERE clause from condition (supports OR/AND with arrays and functions)\n */\n private buildWhereClause<T extends Record<string, unknown>>(\n condition: WhereCondition<T>,\n tableName: string,\n ): {\n sql: string;\n values: Array<string | number | bigint | null | Uint8Array>;\n functionFilters: Array<{\n key: string;\n fn: (value: unknown) => boolean;\n }>;\n hasOrWithFunctionFilters: boolean;\n } {\n const values: Array<string | number | bigint | null | Uint8Array> = [];\n const functionFilters: Array<{ key: string; fn: (value: unknown) => boolean }> = [];\n let hasOrWithFunctionFilters = false;\n\n const buildCondition = (cond: WhereCondition<T>, isInOr = false): string => {\n // Handle array (OR conditions)\n if (Array.isArray(cond)) {\n const clauses = cond\n .map((item) => {\n const clause = Array.isArray(item) ? buildCondition(item, true) : buildCondition(item, true);\n return clause ? `(${clause})` : '';\n })\n .filter((clause) => clause !== ''); // Filter out empty clauses\n\n return clauses.join(' OR ');\n }\n\n // Handle object (AND conditions)\n const conditions: string[] = [];\n let hasFunctionFilter = false;\n for (const [key, value] of Object.entries(cond)) {\n if (typeof value === 'function') {\n // Function filter - will be applied later\n functionFilters.push({ key, fn: value as (value: unknown) => boolean });\n hasFunctionFilter = true;\n } else {\n // Regular value\n conditions.push(`${this.quoteIdentifier(key)} = ?`);\n values.push(this.normalizeValue(value, this.columnOf(tableName, key)));\n }\n }\n\n if (isInOr && hasFunctionFilter) {\n hasOrWithFunctionFilters = true;\n }\n\n return conditions.join(' AND ');\n };\n\n const sql = buildCondition(condition);\n return { sql, values, functionFilters, hasOrWithFunctionFilters };\n }\n\n /**\n * Apply OR condition with function filters by evaluating each row against the condition\n */\n private applyOrConditionWithFilters<T extends Record<string, unknown>>(rows: T[], condition: WhereCondition<T>): T[] {\n return rows.filter((row) => this.matchesOrCondition(row, condition));\n }\n\n /**\n * Check if a row matches an OR/AND condition (recursively)\n */\n private matchesOrCondition<T extends Record<string, unknown>>(row: T, condition: WhereCondition<T>): boolean {\n // Handle array (OR conditions)\n if (Array.isArray(condition)) {\n return condition.some((item) => this.matchesOrCondition(row, item));\n }\n\n // Handle object (AND conditions)\n return Object.entries(condition).every(([key, value]) => {\n const rowValue = row[key as keyof T];\n if (typeof value === 'function') {\n return (value as (value: unknown) => boolean)(rowValue);\n }\n return rowValue === value;\n });\n }\n\n /**\n * Apply function filters to rows\n */\n private applyFunctionFilters<T extends Record<string, unknown>>(\n rows: T[],\n functionFilters: Array<{ key: string; fn: (value: unknown) => boolean }>,\n ): T[] {\n if (functionFilters.length === 0) return rows;\n\n return rows.filter((row) => {\n return functionFilters.every(({ key, fn }) => {\n const value = row[key as keyof T];\n return fn(value);\n });\n });\n }\n\n /**\n * Get table schema\n */\n /**\n * Validate a row against a table's schema, also for a table left out on load because rows failed\n * validation, so a fix can be checked before it is written to the file\n */\n validateRow(tableName: string, row: JsonObject): Result<JsonObject, ValidationError> {\n // A table left out on load is not among the tables, but its schema was loaded\n if (!this.tables.has(tableName) && !this.validationSchemas.has(tableName)) {\n const error = new Error(`Table '${tableName}' does not exist`) as ValidationError;\n error.name = 'ValidationError';\n error.issues = [{ message: `Table '${tableName}' does not exist` }];\n return err(error);\n }\n try {\n return ok(this.validateAndTransform(tableName, row));\n } catch (error) {\n if (error instanceof Error && error.name === 'ValidationError') return err(error as ValidationError);\n throw error;\n }\n }\n\n getSchema(tableName: string): TableSchema | undefined {\n return this.schemas.get(tableName);\n }\n\n /**\n * Get all table names\n */\n getTableNames(): string[] {\n return Array.from(this.schemas.keys());\n }\n\n /**\n * A database composed from several data directories is read-only: the rows of its tables have no\n * single file to be written back to\n */\n private hasSeveralDataDirs(): boolean {\n return typeof this.config.dataDir !== 'string' && this.config.dataDir.length > 1;\n }\n\n /**\n * Turn query_only back on before running a caller's SQL, since an earlier call may have run\n * `PRAGMA query_only = OFF`\n */\n /**\n * Refuse SQL that would end a transaction() or lift the read-only mode that holds back writes made\n * through the database while it runs. Looked for in each statement as SQLite reads it, so a `;` or a\n * comment cannot hide one\n */\n private refuseUnsafeSql(sql: string, viaTransaction = this.viaTransactionObject): void {\n if (\n this.hasSeveralDataDirs() &&\n this.config.writeDataSets &&\n splitStatements(sql).some((statement) => !isReadOnlyStatement(statement))\n ) {\n throw new Error(\n 'Raw SQL is read-only for composed data sets; use insert, update, or delete to preserve source routing',\n );\n }\n // Not only once begun: the read-only mode is held from the moment a transaction starts until it closes,\n // and a BEGIN while it starts would make its own BEGIN fail with one left open that it never rolls back\n if (!this.inTransaction && !this.transactionStarting && !this.transactionClosing) return;\n for (const statement of splitStatements(sql)) {\n // Closed by default: SQL run through the database while a transaction runs may only read, as any\n // other statement or pragma could change the transaction, and none can be listed one by one\n if (this.inTransaction && !viaTransaction && !isReadOnlyStatement(statement)) {\n throw new Error(\n `'${sql.trim()}' is not a read: while a transaction runs, SQL that changes anything must go through the callback's tx`,\n );\n }\n if (/^(BEGIN|COMMIT|END|ROLLBACK(?!\\s+(TRANSACTION\\s+)?TO\\b))\\b/i.test(statement)) {\n throw new Error(\n `'${sql.trim()}' would end the transaction before its files are written back; return from the callback to commit, or throw to roll back`,\n );\n }\n // Not once begun, when a SAVEPOINT is a transaction nested in it and does no harm\n if (!this.inTransaction && /^SAVEPOINT\\b/i.test(statement)) {\n throw new Error(`'${sql.trim()}' would open a transaction of its own while the transaction starts`);\n }\n // Only setting it: reading the pragma changes nothing, and reads through the database stay available\n if (\n /^PRAGMA\\s+(?:(?:\\w+|\"[^\"]*\"|'[^']*'|`[^`]*`|\\[[^\\]]*\\])\\s*\\.\\s*)?(?:query_only|\"query_only\"|'query_only'|`query_only`|\\[query_only\\])\\s*[=(]/i.test(\n statement,\n )\n ) {\n throw new Error(\n `'${sql.trim()}' would lift the read-only mode that refuses writes made while a transaction runs`,\n );\n }\n }\n }\n\n private isReadOnlyDataSet(): boolean {\n return this.hasSeveralDataDirs() && !this.config.writeDataSets;\n }\n\n private enforceReadOnlySql(): void {\n if (this.isReadOnlyDataSet()) {\n this.db.exec('PRAGMA query_only = ON');\n }\n }\n\n /** Writable, and not while a transaction writes back the rows it has already read */\n private assertMutable(tableName: string): void {\n this.assertWritable(tableName);\n this.refuseWhileTransactionSettles(`write to table '${tableName}'`);\n }\n\n /**\n * Refuse a change while a transaction starts or writes its files back: one made while it starts would\n * be written back with rows the transaction may roll back, and one made while it closes would be\n * committed without reaching the files. Also refuse one made through the database itself while the\n * callback runs, which would be committed or rolled back with the transaction unnoticed by its caller\n */\n private refuseWhileTransactionSettles(action: string, viaTransaction = this.viaTransactionObject): void {\n if (this.inTransaction && !viaTransaction) {\n throw new Error(\n `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`,\n );\n }\n if (this.transactionStarting) {\n throw new Error(`Cannot ${action} while a transaction is starting; ${action.split(' ')[0]} once it has finished`);\n }\n if (this.transactionClosing) {\n throw new Error(\n `Cannot ${action} while a transaction writes its files back; ${action.split(' ')[0]} once it has finished`,\n );\n }\n }\n\n /**\n * Run a query() with the database read-only while a transaction starts or writes its files back.\n * Not refused outright as execute() is: a query that only reads changes nothing the files would miss\n */\n private readOnlyWhileTransactionSettles<T>(run: () => T, viaTransaction = this.viaTransactionObject): T {\n if (\n !this.hasSeveralDataDirs() &&\n !this.transactionStarting &&\n !this.transactionClosing &&\n !(this.inTransaction && !viaTransaction)\n ) {\n return run();\n }\n this.db.exec('PRAGMA query_only = ON');\n try {\n return run();\n } catch (error) {\n if (/readonly/i.test(toError(error).message)) this.refuseWhileTransactionSettles('change rows', viaTransaction);\n throw error;\n } finally {\n if (!this.isReadOnlyDataSet()) this.db.exec('PRAGMA query_only = OFF');\n }\n }\n\n private assertWritable(tableName?: string): void {\n if (this.isReadOnlyDataSet()) {\n const target = tableName ? `table '${tableName}'` : 'the database';\n throw new Error(\n `Cannot write to ${target}: dataDir lists several directories, so its rows have no single file to be written back to`,\n );\n }\n }\n\n /**\n * Sync a specific table back to its JSONL file\n * Syncs of the same table run one after another: auto-sync is fire-and-forget, and a write-back\n * that reads the file first must never see a file another sync is halfway through writing.\n */\n private async syncTable(tableName: string, options?: InternalSyncOptions): Promise<void> {\n const pending = this.syncQueue.get(tableName) ?? Promise.resolve();\n const current = pending.then(() => this.writeTable(tableName, options));\n\n this.syncQueue.set(\n tableName,\n current.catch(() => {}),\n );\n\n return current;\n }\n\n /**\n * Write a table back to its JSONL file\n * Uses backward transformation when available\n */\n private async writeTable(tableName: string, options?: InternalSyncOptions): Promise<void> {\n await this.writeFilesTogether(await this.prepareWriteBack(tableName, options));\n }\n\n /**\n * The rows a table is written back as, laid over the lines of its file; fails when the file changed\n * since this database last read or wrote it\n */\n private async prepareWriteBack(tableName: string, options?: InternalSyncOptions): Promise<PreparedWriteBack[]> {\n this.assertWritable(tableName);\n const config = this.tables.get(tableName);\n if (!config) throw new Error(`Table ${tableName} not found`);\n const stored = this.readStoredRows(tableName);\n if (!this.hasSeveralDataDirs()) {\n return [await this.prepareFileWriteBack(tableName, config.jsonlPath, stored, options)];\n }\n const origins = this.rowOriginsByRowid.get(tableName);\n const byFile = new Map<string, number[]>(\n [this.config.dataDir].flat().map((dir) => [join(dir, `${tableName}.jsonl`), []]),\n );\n stored.rowids.forEach((rowid, index) => {\n const origin = origins?.get(rowid);\n if (!origin) throw new Error(`Row ${rowid} of '${tableName}' has no data directory; insert with a dataDir`);\n const indexes = byFile.get(origin.file) ?? [];\n indexes.push(index);\n byFile.set(origin.file, indexes);\n });\n const prepared: PreparedWriteBack[] = [];\n for (const [file, indexes] of byFile) {\n indexes.sort(\n (a, b) =>\n (origins!.get(stored.rowids[a])!.rowIndex < 0 ? Infinity : origins!.get(stored.rowids[a])!.rowIndex) -\n (origins!.get(stored.rowids[b])!.rowIndex < 0 ? Infinity : origins!.get(stored.rowids[b])!.rowIndex),\n );\n const rows = {\n rowids: indexes.map((i) => stored.rowids[i]),\n rows: indexes.map((i) => stored.rows[i]),\n lineRows: indexes.map((i) => stored.lineRows[i]),\n };\n const fileWrite = await this.prepareFileWriteBack(tableName, file, rows, options);\n if (!fileWrite.unchanged) prepared.push(fileWrite);\n }\n return prepared;\n }\n\n private async prepareFileWriteBack(\n tableName: string,\n jsonlPath: string,\n stored: ReturnType<LinesDB<Tables>['readStoredRows']>,\n options?: InternalSyncOptions,\n ): Promise<PreparedWriteBack> {\n const { rowids, rows: deserializedRows, lineRows } = stored;\n const generation = this.changeGenerations.get(tableName) ?? 0;\n let finalRows = lineRows;\n const previousContent = await readFile(jsonlPath, 'utf-8').catch((error: NodeJS.ErrnoException) => {\n if (error.code === 'ENOENT') return undefined;\n throw error;\n });\n const existingRows = await this.readUnchangedRows(jsonlPath);\n\n const matches = this.hasSeveralDataDirs()\n ? rowids.map((rowid) => existingRows[this.rowOriginsByRowid.get(tableName)!.get(rowid)!.rowIndex])\n : undefined;\n\n // An empty list means no field is written back, not that every field is\n const fields = options?.fields ?? this.config.writeBackFields;\n if ((options?.writeFilledValues ?? this.config.writeFilledValues ?? 'all') === 'primaryKey') {\n finalRows = this.keepWrittenFields(\n tableName,\n rowids,\n deserializedRows,\n finalRows,\n existingRows,\n fields,\n matches,\n ).map(({ written }) => written);\n }\n // Not added before narrowing: a field the line holds that the row lacks reads as a renamed one there\n const columns = new Set(this.schemas.get(tableName)?.columns.map((column) => column.name));\n const readLines = this.linesWithUnknownFields.get(tableName);\n finalRows = finalRows.map((row, index) => {\n const line = readLines?.get(rowids[index]);\n return line ? keepUnknownFields(line, row, columns) : row;\n });\n finalRows = this.mergeWithExistingLines(tableName, existingRows, finalRows, {\n fields,\n strictFields: options?.strictFields ?? false,\n matches,\n });\n\n return {\n tableName,\n jsonlPath,\n rows: finalRows,\n previousContent,\n generation,\n ...(matches\n ? { rowids, unchanged: JsonlWriter.serialize(existingRows) === JsonlWriter.serialize(finalRows) }\n : {}),\n };\n }\n\n /**\n * Every row of a table in rowid order - the order the file was read in - as stored and as its line\n * would hold it, after the backward transformation\n */\n private readStoredRows(tableName: string): { rowids: string[]; rows: JsonObject[]; lineRows: JsonObject[] } {\n const stored = this.queryInternal<JsonObject>(\n `SELECT rowid AS \"${ROWID_ALIAS}\", * FROM ${this.quoteTableName(tableName)} ORDER BY rowid`,\n );\n const rowids = stored.map((row) => String(row[ROWID_ALIAS]));\n const rows = stored.map(({ [ROWID_ALIAS]: _rowid, ...row }) => this.deserializeRow(tableName, row));\n\n const validationSchema = this.validationSchemas.get(tableName);\n const lineRows =\n validationSchema && hasBackward(validationSchema)\n ? rows.map((row) => (validationSchema as BiDirectionalSchema<Table, Table>).backward!(row) as JsonObject)\n : rows;\n return { rowids, rows, lineRows };\n }\n\n /**\n * Narrow each row to the fields a user wrote - the ones its line holds, plus those set since and\n * minus those reset to their default - its primary key and the fields named to be written back, so\n * a value the schema fills in stays out of the file\n */\n private keepWrittenFields(\n tableName: string,\n rowids: string[],\n rows: JsonObject[],\n lineRows: JsonObject[],\n existingRows: JsonObject[],\n namedFields: readonly string[] = [],\n matchedLines?: Array<JsonObject | undefined>,\n ): Array<{ written: JsonObject; narrowed: boolean }> {\n const pkName = this.schemas.get(tableName)?.columns.find((col) => col.primaryKey)?.name;\n // Not left to the recorded changes: an ON DELETE / ON UPDATE action changes these columns in SQLite\n // without a write through this database\n const actionColumns = (this.schemas.get(tableName)?.foreignKeys ?? [])\n .filter((fk) => [fk.onDelete, fk.onUpdate].some((action) => action === 'CASCADE' || action === 'SET NULL'))\n .map((fk) => fk.column);\n const lines = matchedLines ?? this.matchExistingRows(tableName, lineRows, existingRows, { required: false });\n const changes = this.fieldChanges.get(tableName);\n\n return lineRows.map((lineRow, index) => {\n const line = lines?.[index];\n const rowChanges = changes?.get(rowids[index]);\n // Not narrowed when the backward transformation renames fields: the line's keys name other fields\n const renamesFields = Object.keys(lineRow).some((key) => !Object.hasOwn(rows[index], key));\n // Not narrowed without a line unless the row was inserted: a row whose key changed has lost its\n // line too, and narrowing it would drop the fields that line held\n if (renamesFields || this.rawSqlTables.has(tableName) || (!line && !rowChanges?.inserted)) {\n return { written: lineRow, narrowed: false };\n }\n\n const keep = new Set([...Object.keys(line ?? {}), ...(rowChanges?.set ?? []), ...actionColumns]);\n for (const key of rowChanges?.reset ?? []) keep.delete(key);\n for (const key of namedFields) keep.add(key);\n if (pkName) keep.add(pkName);\n // Not the stored value for a row nothing wrote to: a schema computes a value that may differ from what\n // the line holds, and an edit elsewhere in the file is no reason to write it into this line\n const untouched = line !== undefined && !rowChanges?.inserted && !rowChanges?.set.size && !rowChanges?.reset.size;\n return {\n written: Object.fromEntries(\n Object.entries(lineRow)\n .filter(([key]) => keep.has(key))\n .map(([key, value]) => [\n key,\n untouched && Object.hasOwn(line, key) && !actionColumns.includes(key) && !namedFields.includes(key)\n ? line[key]\n : value,\n ]),\n ) as JsonObject,\n narrowed: true,\n };\n });\n }\n\n private rowidsWhere(\n tableName: string,\n whereSql: string,\n values: (string | number | bigint | null | Uint8Array)[],\n ): string[] {\n return this.queryInternal<JsonObject>(\n `SELECT rowid AS \"${ROWID_ALIAS}\" FROM ${this.quoteTableName(tableName)} WHERE ${whereSql}`,\n values,\n ).map((row) => String(row[ROWID_ALIAS]));\n }\n\n /**\n * Forget the field changes of deleted rows: a deleted row's rowid can be given to a row inserted\n * later, which must not inherit them\n */\n private moveRowMetadata(tableName: string, from: string, to: string): void {\n for (const byRow of [\n this.fieldChanges.get(tableName),\n this.linesWithUnknownFields.get(tableName),\n this.rowOriginsByRowid.get(tableName),\n ]) {\n const kept = byRow?.get(from);\n if (!byRow || kept === undefined) continue;\n byRow.delete(from);\n byRow.set(to, kept as never);\n }\n }\n\n /** Forget the lines kept for rows that are gone, such as rows raw SQL or a foreign-key action deleted */\n private forgetLinesOfGoneRows(tableNames: Iterable<string>): void {\n for (const tableName of tableNames) {\n const lines = this.linesWithUnknownFields.get(tableName);\n if (!lines || lines.size === 0) continue;\n let stored: JsonObject[];\n try {\n stored = this.queryInternal<JsonObject>(\n `SELECT rowid AS \"${ROWID_ALIAS}\" FROM ${this.quoteTableName(tableName)}`,\n );\n } catch {\n // Not thrown: raw SQL may have dropped the table, and the error worth reporting is that SQL's own\n continue;\n }\n const present = new Set(stored.map((row) => String(row[ROWID_ALIAS])));\n for (const rowid of lines.keys()) if (!present.has(rowid)) lines.delete(rowid);\n }\n }\n\n private forgetFieldChanges(tableName: string, rowids: string[]): void {\n for (const rowid of rowids) {\n this.fieldChanges.get(tableName)?.delete(rowid);\n this.linesWithUnknownFields.get(tableName)?.delete(rowid);\n }\n }\n\n private noteChange(tableName: string): void {\n this.changeGenerations.set(tableName, (this.changeGenerations.get(tableName) ?? 0) + 1);\n }\n\n private noteFieldChanges(\n tableName: string,\n rowid: number | bigint,\n changes: { set?: readonly string[]; reset?: readonly string[]; inserted?: boolean },\n ): void {\n this.noteChange(tableName);\n const byRow = this.fieldChanges.get(tableName) ?? new Map<string, FieldChanges>();\n const rowChanges = byRow.get(String(rowid)) ?? {\n set: new Set<string>(),\n reset: new Set<string>(),\n inserted: false,\n };\n if (changes.inserted) rowChanges.inserted = true;\n for (const key of changes.set ?? []) {\n rowChanges.set.add(key);\n rowChanges.reset.delete(key);\n }\n for (const key of changes.reset ?? []) {\n rowChanges.reset.add(key);\n rowChanges.set.delete(key);\n }\n byRow.set(String(rowid), rowChanges);\n this.fieldChanges.set(tableName, byRow);\n }\n\n /**\n * Store the value the schema fills in for each reset field, as validating the row without the field\n * gives it, and remember the field as reset so it leaves the line\n */\n /** The value the schema fills in for each reset field of each target, validating the row without them */\n private computeResets(\n tableName: string,\n targets: JsonObject[],\n data: JsonObject,\n fields: readonly string[],\n ): Array<{ rowid: number | bigint; values: ReturnType<LinesDB<Tables>['normalizeValue']>[] }> {\n return targets.map((target) => {\n const { [ROWID_ALIAS]: rowid, ...stored } = target;\n const row = { ...this.deserializeRow(tableName, stored), ...data };\n for (const field of fields) delete row[field];\n const validated = this.validateAndTransform(tableName, row);\n return {\n rowid: rowid as number | bigint,\n values: fields.map((field) => this.normalizeValue(validated[field], this.columnOf(tableName, field))),\n };\n });\n }\n\n /** Store the values computeResets gave, and remember the fields as reset so they leave the line */\n private applyResets(\n tableName: string,\n resets: Array<{ rowid: number | bigint; values: ReturnType<LinesDB<Tables>['normalizeValue']>[] }>,\n fields: readonly string[],\n ): { changes: number | bigint; lastInsertRowid: number | bigint } {\n let changes = 0n;\n const setClauses = fields.map((field) => `${this.quoteIdentifier(field)} = ?`).join(', ');\n for (const { rowid, values } of resets) {\n const result = this.executeInternal(\n `UPDATE ${this.quoteTableName(tableName)} SET ${setClauses} WHERE rowid = ?`,\n [...values, rowid],\n );\n changes += BigInt(result.changes);\n this.noteFieldChanges(tableName, rowid, { reset: fields });\n }\n return { changes, lastInsertRowid: 0 };\n }\n\n /**\n * Every row of a table with the fields the schema filled in rather than the file: the ones its line\n * does not hold and no write set, which a write-back leaves out of the file\n */\n async findWithDefaults<K extends keyof Tables & string>(\n tableName: K,\n ): Promise<Result<Array<{ row: Tables[K]; defaulted: string[] }>, Error>> {\n try {\n const tableConfig = this.tables.get(tableName);\n if (!tableConfig || !this.schemas.has(tableName)) {\n throw new Error(`Table '${tableName}' is not loaded`);\n }\n // Not read as the file is now: lines another tool changed would be matched to the rows read before\n await this.waitForPendingSyncs();\n const { rowids, rows, lineRows } = this.readStoredRows(tableName);\n const fileRows = new Map<string, JsonObject[]>();\n for (const file of this.hasSeveralDataDirs()\n ? new Set([\n ...(tableConfig.jsonlPaths ?? [tableConfig.jsonlPath]),\n ...[...(this.rowOriginsByRowid.get(tableName)?.values() ?? [])].map((origin) => origin.file),\n ])\n : [tableConfig.jsonlPath]) {\n fileRows.set(file, await this.readUnchangedRows(file));\n }\n const existingRows = [...fileRows.values()].flat();\n const matches =\n this.hasSeveralDataDirs() && this.config.writeDataSets\n ? rowids.map((rowid) => {\n const origin = this.rowOriginsByRowid.get(tableName)?.get(rowid);\n return origin && fileRows.get(origin.file)?.[origin.rowIndex];\n })\n : undefined;\n const kept = this.keepWrittenFields(\n tableName,\n rowids,\n rows,\n lineRows,\n existingRows,\n this.config.writeBackFields,\n matches,\n );\n return ok(\n rows.map((row, index) => ({\n row: row as Tables[K],\n defaulted: kept[index].narrowed\n ? Object.keys(row).filter((key) => !Object.hasOwn(kept[index].written, key))\n : [],\n })),\n );\n } catch (error) {\n return err(toError(error));\n }\n }\n\n private async writePrepared(prepared: PreparedWriteBack): Promise<void> {\n const { jsonlPath, rows, previousContent } = prepared;\n if (this.hasSeveralDataDirs() || this.config.writeDataSets) {\n await replaceFile(jsonlPath, (temporary) => JsonlWriter.write(temporary, rows), previousContent);\n } else {\n await JsonlWriter.write(jsonlPath, rows);\n }\n prepared.completed = true;\n const contentHash = hashJsonlContent(JsonlWriter.serialize(rows));\n this.fileHashes.set(jsonlPath, contentHash);\n this.observedHashes.set(jsonlPath, contentHash);\n }\n\n /**\n * Write a table back to its file, or leave it to the running transaction, which writes back the\n * tables it changed once its callback is done\n */\n private afterWrite(tableName: string, changes: number | bigint): void {\n // Not counted when no row changed: writing the table back could then fail on a file it never touched\n if (BigInt(changes) === 0n && this.transactionChanges) return;\n const tableNames = [tableName, ...this.tablesChangedByForeignKeyActions(tableName)];\n // Not left to the write-back: a row inserted before it can take the rowid of a row deleted here\n this.forgetLinesOfGoneRows(tableNames);\n if (this.transactionChanges) {\n if (this.transactionChanges !== 'all') for (const name of tableNames) this.transactionChanges.add(name);\n return;\n }\n for (const name of tableNames) {\n this.syncTable(name).catch((err) => {\n console.error(`Failed to sync table ${name}:`, err);\n });\n }\n }\n\n /**\n * The tables whose rows an ON DELETE / ON UPDATE action can change when a table's rows change,\n * following the actions on to the tables they change in turn\n */\n private tablesChangedByForeignKeyActions(tableName: string): string[] {\n const found = new Set<string>();\n const visit = (referenced: string) => {\n for (const [name, schema] of this.schemas) {\n if (found.has(name) || name === tableName) continue;\n const acts = (schema.foreignKeys ?? []).some(\n (fk) =>\n fk.references.table === referenced &&\n [fk.onDelete, fk.onUpdate].some((action) => action === 'CASCADE' || action === 'SET NULL'),\n );\n if (acts) {\n found.add(name);\n visit(name);\n }\n }\n };\n visit(tableName);\n return Array.from(found);\n }\n\n private tablesChangedInTransaction(): string[] {\n const changes = this.transactionChanges;\n return changes === 'all' ? Array.from(this.schemas.keys()) : Array.from(changes ?? []);\n }\n\n /**\n * Write several tables back, checking every file before writing any, so a file changed on disk\n * fails the write-back before it has written part of it\n */\n private async writeBackTogether(tableNames: string[]): Promise<PreparedWriteBack[]> {\n await this.waitForPendingSyncs();\n const prepared = [];\n for (const tableName of tableNames) {\n prepared.push(...(await this.prepareWriteBack(tableName)));\n }\n return this.writeFilesTogether(prepared);\n }\n\n private async writeFilesTogether(prepared: PreparedWriteBack[]): Promise<PreparedWriteBack[]> {\n const written: PreparedWriteBack[] = [];\n try {\n for (const table of prepared) {\n // Counted as written before the write: a write that fails can still have truncated the file\n written.push(table);\n await this.writePrepared(table);\n }\n } catch (error) {\n throw await this.restoreAll(written, error);\n }\n for (const { tableName, jsonlPath, generation, rowids } of written) {\n if ((this.changeGenerations.get(tableName) ?? 0) === generation) {\n this.fieldChanges.delete(tableName);\n this.rawSqlTables.delete(tableName);\n }\n if (rowids) {\n const origins = this.rowOriginsByRowid.get(tableName)!;\n rowids.forEach((rowid, rowIndex) => origins.set(rowid, { file: jsonlPath, rowIndex }));\n if (!this.scannedJsonlFiles.includes(jsonlPath)) this.scannedJsonlFiles.push(jsonlPath);\n }\n }\n return written;\n }\n\n /**\n * Put back every written file, going on past one that cannot be put back, and give the error to\n * throw: the one that made the write-back fail, naming the files left holding what was written\n */\n private async restoreAll(written: PreparedWriteBack[], error: unknown): Promise<unknown> {\n const notRestored: string[] = [];\n for (const table of written) {\n await this.restorePrepared(table).catch(() => notRestored.push(table.jsonlPath));\n }\n if (notRestored.length === 0) return error;\n const failure = toError(error);\n const recoveryError = new Error(\n `${failure.message}\\nThese files could not be put back and hold rows the database does not: ${notRestored.join(', ')}`,\n { cause: error },\n );\n if (failure.name === 'JsonlConflictError') {\n recoveryError.name = failure.name;\n (recoveryError as JsonlConflictError).file = (failure as JsonlConflictError).file;\n }\n return recoveryError;\n }\n\n /**\n * Put back the content a file held before {@link writePrepared} wrote over it. The file is expected\n * to hold that content even when putting it back fails, so a file left holding the written rows\n * counts as changed on disk instead of matching the database\n */\n private async restorePrepared({ jsonlPath, previousContent, rows, completed }: PreparedWriteBack): Promise<void> {\n if (this.hasSeveralDataDirs() || this.config.writeDataSets) {\n if (!completed) return;\n const current = await readFile(jsonlPath, 'utf8').catch((error: NodeJS.ErrnoException) => {\n if (error.code === 'ENOENT') return undefined;\n throw error;\n });\n const expected = JsonlWriter.serialize(rows);\n if (current !== expected) throw new Error(`JSONL file '${jsonlPath}' changed during rollback`);\n }\n if (previousContent === undefined) {\n this.fileHashes.delete(jsonlPath);\n this.observedHashes.delete(jsonlPath);\n if (this.hasSeveralDataDirs() || this.config.writeDataSets)\n await replaceFile(jsonlPath, undefined, JsonlWriter.serialize(rows));\n else await rm(jsonlPath, { force: true });\n return;\n }\n this.fileHashes.set(jsonlPath, hashJsonlContent(previousContent));\n this.observedHashes.set(jsonlPath, hashJsonlContent(previousContent));\n if (this.hasSeveralDataDirs() || this.config.writeDataSets) {\n await replaceFile(\n jsonlPath,\n (temporary) => writeFile(temporary, previousContent, 'utf8'),\n JsonlWriter.serialize(rows),\n );\n } else {\n await writeFile(jsonlPath, previousContent, 'utf-8');\n }\n }\n\n /**\n * Lay the rows out over the lines the JSONL file already holds.\n *\n * Rows keep the order the file lists them in - the database returns rows in its own order, and\n * an integer primary key is SQLite's rowid, so writing rows back in query order would reshuffle\n * the file. Rows the file never had follow, in database order.\n *\n * With `fields`, only those fields are taken from the row and every other field keeps the value\n * its line already had, so values a validation hook computed and fields the file omitted are\n * never materialized. Fields this table does not have are simply not written, so one list can\n * cover a directory of tables that do not all share it; a sync asked for a single table by name\n * rejects them instead, since there the caller named both the table and the fields.\n */\n private mergeWithExistingLines(\n tableName: string,\n existingRows: JsonObject[],\n rows: JsonObject[],\n options: { fields?: readonly string[]; strictFields: boolean; matches?: Array<JsonObject | undefined> },\n ): JsonObject[] {\n if (rows.length === 0) {\n return rows;\n }\n\n const { fields } = options;\n const tableFields = fields?.filter((field) => rows.some((row) => field in row));\n if (fields && tableFields && options.strictFields && tableFields.length < fields.length) {\n const unknownFields = fields.filter((field) => !tableFields.includes(field));\n throw new Error(\n `Cannot write back field(s) [${unknownFields.join(', ')}] for table '${tableName}': ` +\n `no such field in the rows written back to the file.`,\n );\n }\n\n // Without `fields` the rows are written whole, so matching them to their line only decides the\n // order: fall back to database order rather than failing when they cannot be matched\n const existing =\n options.matches ?? this.matchExistingRows(tableName, rows, existingRows, { required: fields !== undefined });\n if (!existing) {\n return rows;\n }\n\n const rowByLine = new Map<JsonObject, JsonObject>();\n const newRows: JsonObject[] = [];\n rows.forEach((row, index) => {\n const base = existing[index];\n if (base) {\n rowByLine.set(base, row);\n } else {\n newRows.push(row);\n }\n });\n\n const writtenRows = existingRows\n .filter((base) => rowByLine.has(base))\n .map((base) => {\n const row = rowByLine.get(base)!;\n // A row missing a named field - a backward transformation can drop it - keeps what the file\n // holds, and a field the line did not have is inserted where the schema declares it\n return tableFields\n ? mergeFields(base, row, { fields: tableFields, keyOrder: this.keyOrders.get(tableName) })\n : row;\n });\n\n return [...writtenRows, ...newRows];\n }\n\n /**\n * Pair each row with the JSONL line it came from, indexed the same way as `rows`.\n * Returns undefined when the rows cannot be matched and the caller can do without it.\n */\n private matchExistingRows(\n tableName: string,\n rows: JsonObject[],\n existingRows: JsonObject[],\n options: { required: boolean },\n ): Array<JsonObject | undefined> | undefined {\n // Nothing in the file to preserve, so every row is one the file never had\n if (existingRows.length === 0) {\n return rows.map(() => undefined);\n }\n\n const pkName = this.schemas.get(tableName)?.columns.find((col) => col.primaryKey)?.name;\n const pkValues = pkName ? existingRows.map((row) => row[pkName]) : [];\n const hasUsablePk =\n pkName !== undefined &&\n pkValues.every((value) => value !== undefined && value !== null) &&\n new Set(pkValues.map((value) => String(value))).size === pkValues.length;\n\n if (hasUsablePk) {\n const byPk = new Map(existingRows.map((row, index) => [String(pkValues[index]), row]));\n return rows.map((row) => {\n const pkValue = row[pkName!];\n return pkValue === undefined || pkValue === null ? undefined : byPk.get(String(pkValue));\n });\n }\n\n // No usable primary key in the file: fall back to matching rows to lines by position.\n // Only safe while the row count is unchanged, since anything else means rows were\n // added or removed and positions no longer line up.\n if (rows.length !== existingRows.length) {\n if (!options.required) {\n return undefined;\n }\n throw new Error(\n `Cannot write back selected fields for table '${tableName}': ` +\n `the file has ${existingRows.length} row(s) but the table has ${rows.length}, and ` +\n `${pkName ? `column '${pkName}' is not usable as a primary key in the file` : 'the table has no primary key'}, ` +\n `so rows cannot be matched to their existing lines.`,\n );\n }\n\n return existingRows;\n }\n\n /**\n * Read the rows a JSONL file currently holds, treating a missing file as empty, and refuse to go on\n * when the file is not the one this database last read or wrote: writing over it would drop the\n * changes made to it since\n */\n private async readUnchangedRows(jsonlPath: string): Promise<JsonObject[]> {\n const result = await JsonlReader.readSnapshot(jsonlPath);\n if (!result.ok && (result.error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw result.error;\n }\n const snapshot = result.ok ? result.value : { rows: ok<JsonObject[]>([]), contentHash: undefined };\n\n const knownHash = this.fileHashes.get(jsonlPath);\n if (\n (knownHash !== undefined && snapshot.contentHash !== knownHash) ||\n (this.config.writeDataSets && !this.scannedJsonlFiles.includes(jsonlPath) && snapshot.contentHash !== undefined)\n ) {\n const conflictError = new Error(\n `JSONL file '${jsonlPath}' was changed after the database read it, so it was not overwritten. ` +\n `Create the database again and call initialize() to load the current file, then retry the write.`,\n ) as JsonlConflictError;\n conflictError.name = 'JsonlConflictError';\n conflictError.file = jsonlPath;\n throw conflictError;\n }\n\n return unwrap(snapshot.rows);\n }\n\n /**\n * Tell whether the files the tables were loaded from changed since this database last read or\n * wrote them: a JSONL file was edited, added or removed, or a table's schema file was edited, added\n * or removed. When they did, the database holds rows or a schema the files no longer have; create it\n * again and call initialize() to load the current files.\n */\n async hasExternalChanges(): Promise<Result<boolean, Error>> {\n try {\n return ok((await this.findExternalChangesInternal()).length > 0);\n } catch (error) {\n return err(toError(error));\n }\n }\n\n /**\n * The files that changed since this database last read or wrote them, as {@link hasExternalChanges}\n * tells: each JSONL file edited, added or removed, each schema file edited, added or removed, and each\n * project file a schema imports edited, added or removed\n */\n async findExternalChanges(): Promise<Result<string[], Error>> {\n try {\n return ok(await this.findExternalChangesInternal());\n } catch (error) {\n return err(toError(error));\n }\n }\n\n private async findExternalChangesInternal(): Promise<string[]> {\n // A write-back still in flight has written its file before it records the file's hash\n await this.waitForPendingSyncs();\n const changed = new Set<string>();\n\n for (const [file, knownHash] of this.observedHashes) {\n const content = await readFile(file, 'utf-8').catch((error: NodeJS.ErrnoException) => {\n if (error.code === 'ENOENT') return undefined;\n throw error;\n });\n if (content === undefined || hashJsonlContent(content) !== knownHash) changed.add(file);\n }\n\n // Each file is read once, whatever the number of tables importing it, and is changed for any of them that read another version\n const knownHashes = new Map<string, Set<string>>();\n for (const files of this.schemaDependencyHashes.values()) {\n for (const [file, knownHash] of files) knownHashes.set(file, (knownHashes.get(file) ?? new Set()).add(knownHash));\n }\n for (const [file, hashes] of knownHashes) {\n const content = await readFile(file).catch((error: NodeJS.ErrnoException) => {\n if (error.code === 'ENOENT') return undefined;\n throw error;\n });\n const current = content === undefined ? MISSING_HASH : hashContent(content);\n if ([...hashes].some((hash) => hash !== current)) changed.add(file);\n }\n\n const tables = await DirectoryScanner.scanDirectory(this.config.dataDir);\n const scanned = new Set(listJsonlFiles(tables));\n for (const file of this.scannedJsonlFiles) if (!scanned.has(file)) changed.add(file);\n for (const file of scanned) if (!this.scannedJsonlFiles.includes(file)) changed.add(file);\n\n for (const name of new Set([...this.schemaFileStates.keys(), ...tables.keys()])) {\n const knownState = this.schemaFileStates.get(name) ?? '';\n const config = tables.get(name);\n const state = config ? await this.schemaFileState(name, config) : await this.stateOfKnownSchemaFile(knownState);\n if (state !== knownState) changed.add((state || knownState).split('\\0')[0]);\n }\n return [...changed];\n }\n\n /** The state of the schema file a state names, for a table whose JSONL file is gone */\n private async stateOfKnownSchemaFile(knownState: string): Promise<string> {\n if (!knownState) return '';\n const schemaPath = knownState.split('\\0')[0];\n const content = await readFile(schemaPath, 'utf-8').catch((error: NodeJS.ErrnoException) => {\n if (error.code === 'ENOENT') return undefined;\n throw error;\n });\n return content === undefined ? '' : `${schemaPath}\\0${hashJsonlContent(content)}`;\n }\n\n // Kept for each table, as reading one table again must not hide an edit from another that shares the file\n private recordSchemaDependencies(\n imports: SchemaImports,\n tableNames: Iterable<string>,\n schemaPaths: Map<string, string>,\n replace: boolean,\n ): void {\n // Not cleared whole: a table the read did not reach, as it stopped at another that failed, keeps its validator and its files\n if (replace) {\n for (const name of this.schemaDependencyHashes.keys()) {\n if (!schemaPaths.has(name)) this.schemaDependencyHashes.delete(name);\n }\n }\n for (const name of tableNames) {\n const schemaPath = schemaPaths.get(name);\n if (schemaPath) this.schemaDependencyHashes.set(name, imports.dependencies(schemaPath));\n else this.schemaDependencyHashes.delete(name);\n }\n }\n\n /**\n * The project files the schemas import, as paths: not the schema files, and not a package from\n * node_modules. Those of one table when it is given. An edit to one of them is among\n * {@link findExternalChanges}\n */\n listSchemaDependencies(tableName?: string): string[] {\n const tables =\n tableName === undefined\n ? [...this.schemaDependencyHashes.values()]\n : [this.schemaDependencyHashes.get(tableName) ?? new Map()];\n return [...new Set(tables.flatMap((files) => [...files.keys()]))];\n }\n\n private async schemaFileState(tableName: string, config: TableConfig): Promise<string> {\n if (config.validationSchema) return '';\n const schemaPath = await this.findTableSchemaFile(tableName, config);\n if (!schemaPath) return '';\n return `${schemaPath}\\0${hashJsonlContent(await readFile(schemaPath, 'utf-8'))}`;\n }\n\n /**\n * Sync database changes back to JSONL files\n * Uses backward transformation when available\n * @param tableName Optional table name to sync. If not provided, syncs all loaded tables\n * @param options Optional sync options, e.g. the fields to write back\n */\n async sync(tableName?: string, options?: SyncOptions): Promise<Result<void, Error>> {\n try {\n await this.syncInternal(tableName, options);\n return ok(undefined);\n } catch (error) {\n return err(toError(error));\n }\n }\n\n private async syncInternal(tableName?: string, options?: SyncOptions): Promise<void> {\n this.refuseWhileTransactionSettles('sync');\n this.assertWritable(tableName);\n if (this.inTransaction) {\n throw new Error(\n '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',\n );\n }\n\n if (tableName) {\n // Sync only the specified table\n if (!this.schemas.has(tableName)) {\n throw new Error(`Table '${tableName}' is not loaded`);\n }\n // The caller named both the table and the fields, so a field it does not have is a mistake\n await this.syncTable(tableName, { ...options, strictFields: options?.fields !== undefined });\n } else {\n // Sync all tables that are loaded (present in schemas map)\n for (const [name] of this.schemas) {\n await this.syncTable(name, options);\n }\n }\n }\n\n /**\n * Execute a function within a transaction\n * Automatically commits on success or rolls back on error.\n *\n * Note: `tx` (the argument `fn` receives) is the same Result-returning API as `this` - a failed\n * `tx.insert()`/`tx.update()`/etc. inside `fn` does not throw and therefore does not roll back the\n * transaction on its own. To abort on such a failure, check the Result and `throw result.error`\n * (or any error) from `fn`; only a thrown error rolls the transaction back.\n */\n async transaction<T>(fn: (tx: LinesDB<Tables>) => Promise<T> | T): Promise<Result<T, Error>> {\n if (this.inTransaction || this.transactionStarting) {\n return err(new Error('Nested transactions are not supported'));\n }\n // Not left to inTransaction: it is set only after the awaits below, which a second call could slip past\n this.transactionStarting = true;\n const token = {};\n\n let fieldChangesBefore: Map<string, Map<string, FieldChanges>> | undefined;\n let rawSqlTablesBefore: Set<string> | undefined;\n let linesWithUnknownFieldsBefore: Map<string, Map<string, JsonObject>> | undefined;\n let originsBefore: Map<string, Map<string, RowOrigin>> | undefined;\n let columnsBefore: Map<string, TableSchema['columns']> | undefined;\n const scannedBefore = [...this.scannedJsonlFiles];\n let written: PreparedWriteBack[] = [];\n try {\n // Not beginning first: a pending auto-sync would then read, and write out, rows still uncommitted\n await this.waitForPendingSyncs();\n originsBefore = new Map([...this.rowOriginsByRowid].map(([name, origins]) => [name, new Map(origins)]));\n // The columns added to a table made from given columns go with the transaction that added them\n columnsBefore = new Map(\n [...this.tablesFromGivenColumns].map((name) => [name, [...(this.schemas.get(name)?.columns ?? [])]]),\n );\n fieldChangesBefore = cloneFieldChanges(this.fieldChanges);\n rawSqlTablesBefore = new Set(this.rawSqlTables);\n linesWithUnknownFieldsBefore = new Map(\n Array.from(this.linesWithUnknownFields, ([tableName, lines]) => [tableName, new Map(lines)]),\n );\n this.db.exec('BEGIN TRANSACTION');\n this.settleUndos = [];\n this.inTransaction = true;\n this.transactionToken = token;\n this.transactionStarting = false;\n this.transactionChanges = new Set();\n\n let result: T;\n try {\n result = await fn(this.scopedToTransaction(token));\n } finally {\n // Not open to writes from here, whether the callback returned or threw: the rows are read for the\n // write-back and the files put back, and a write made during those awaits would join the\n // transaction without reaching the files, or be rolled back after it reported success\n this.transactionClosing = true;\n }\n\n // Written back before COMMIT, so a failed write-back rolls the change back instead of leaving the\n // database holding rows its files do not; a read-only database has no changes to write back\n if (!this.isReadOnlyDataSet()) {\n written = await this.writeBackTogether(this.tablesChangedInTransaction());\n }\n\n this.db.exec('COMMIT');\n this.settleUndos = undefined;\n this.inTransaction = false;\n this.transactionChanges = undefined;\n\n return ok(result);\n } catch (error) {\n this.transactionStarting = false;\n this.transactionChanges = undefined;\n if (originsBefore) this.rowOriginsByRowid = originsBefore;\n for (const [name, columns] of columnsBefore ?? []) {\n const schema = this.schemas.get(name);\n if (schema) schema.columns = columns;\n }\n this.scannedJsonlFiles = scannedBefore;\n if (fieldChangesBefore) this.fieldChanges = fieldChangesBefore;\n if (rawSqlTablesBefore) this.rawSqlTables = rawSqlTablesBefore;\n if (linesWithUnknownFieldsBefore) this.linesWithUnknownFields = linesWithUnknownFieldsBefore;\n // Not only when writing a file fails: a COMMIT failing after the writes leaves files holding rolled-back rows\n const failure = await this.restoreAll(written, error);\n if (this.inTransaction) {\n try {\n this.db.exec('ROLLBACK');\n } catch (_rollbackError) {\n // Report the original error rather than a failure to roll back\n }\n }\n // Not before the ROLLBACK: a read on the connection while the files are put back still sees the\n // rolled-back row, and would read it with the column type it had before the write\n for (const undo of [...(this.settleUndos ?? [])].reverse()) undo();\n this.settleUndos = undefined;\n this.inTransaction = false;\n return err(toError(failure));\n } finally {\n this.transactionClosing = false;\n this.transactionToken = undefined;\n }\n }\n\n /**\n * The object a transaction() callback receives. Calls on it are marked as the transaction's own for as\n * long as they run; a write made through the database itself in the meantime is refused, since writes are\n * synchronous and cannot be queued until the transaction ends\n */\n private scopedToTransaction(token: object): LinesDB<Tables> {\n return new Proxy(this, {\n get: (target, property) => {\n const value: unknown = Reflect.get(target, property, target);\n if (typeof value !== 'function') return value;\n return (...args: unknown[]) => {\n const before = target.viaTransactionObject;\n target.viaTransactionObject = before || target.transactionToken === token;\n try {\n return value.apply(target, args);\n } finally {\n target.viaTransactionObject = before;\n }\n };\n },\n });\n }\n\n /**\n * Wait for every queued sync to finish, so a fire-and-forget auto-sync is not dropped\n */\n private async waitForPendingSyncs(): Promise<void> {\n const awaited = new Set<Promise<void>>();\n // Queued promises never reject: syncTable stores them with their rejection swallowed\n let pending = Array.from(this.syncQueue.values());\n\n while (pending.length > 0) {\n for (const promise of pending) {\n awaited.add(promise);\n }\n await Promise.all(pending);\n pending = Array.from(this.syncQueue.values()).filter((promise) => !awaited.has(promise));\n }\n }\n\n /**\n * Close the database connection\n */\n async close(): Promise<Result<void, Error>> {\n try {\n await this.waitForPendingSyncs();\n try {\n this.db.close();\n } catch (_error) {\n // Ignore errors if database is already closed\n }\n return ok(undefined);\n } catch (error) {\n return err(toError(error));\n }\n }\n\n /**\n * Get a handle for running SQL on the underlying SQLite database. It wraps the connection rather than\n * being it, also outside a transaction: while a transaction() callback runs, SQL that changes rows is\n * refused unless the handle came from the callback's `tx`, and SQL that would end the transaction is\n * refused for every handle. Outside a transaction it runs SQL unchanged.\n */\n getDb(): SQLiteDatabase {\n // Handed out as a wrapper even outside a transaction: a handle kept from before one would otherwise\n // write while its callback awaits, unseen by the write-back, and be committed or rolled back with it\n const token = this.viaTransactionObject ? this.transactionToken : undefined;\n // Not captured as a boolean: a handle kept from an earlier transaction must not count as the running one's\n const viaTransaction = () => token !== undefined && token === this.transactionToken;\n const idle = () => !this.inTransaction && !this.transactionStarting && !this.transactionClosing;\n // Checked each time SQL runs, not when the handle is taken: SQL that would end a transaction must be\n // refused, and one that changes rows tracked, whichever transaction is open by then\n const guarded = <T>(sql: string, run: () => T): T => {\n if (idle() && !this.hasSeveralDataDirs()) return run();\n this.refuseUnsafeSql(sql, viaTransaction());\n return this.readOnlyWhileTransactionSettles(() => this.trackRawSql(run), viaTransaction());\n };\n return {\n prepare: (sql: string) => {\n // Also when prepared: SQLite runs some pragmas then, not only when the statement is stepped\n if (!idle() || this.hasSeveralDataDirs()) this.refuseUnsafeSql(sql, viaTransaction());\n const statement = this.readOnlyWhileTransactionSettles(() => this.db.prepare(sql), viaTransaction());\n return {\n run: (...params: unknown[]) => guarded(sql, () => statement.run(...params)),\n get: (...params: unknown[]) => guarded(sql, () => statement.get(...params)),\n all: (...params: unknown[]) => guarded(sql, () => statement.all(...params)),\n };\n },\n exec: (sql: string) => guarded(sql, () => this.db.exec(sql)),\n close: () => this.db.close(),\n };\n }\n}\n\nfunction listJsonlFiles(tables: Map<string, TableConfig>): string[] {\n return Array.from(tables.values())\n .flatMap((config) => config.jsonlPaths ?? [config.jsonlPath])\n .sort();\n}\n","import { randomBytes } from 'node:crypto';\nimport { chmod, readdir, readFile, realpath, rename, rm, stat, writeFile } from 'node:fs/promises';\nimport { basename, dirname, join } from 'node:path';\nimport { type Result, ok, err, toError } from './result.js';\nimport { hasBackward, type BiDirectionalSchema } from './schema.js';\nimport { findSchemaFile } from './schema-extensions.js';\nimport { createSchemaImports } from './schema-module.js';\nimport type { JsonlConflictError, JsonObject, JsonValue, StandardSchema, Table } from './types.js';\n\n/** Computes the values a row gets, from the row as its line holds it */\nexport type RowFiller = (row: JsonObject) => Record<string, unknown>;\n\nexport interface FillFieldsOptions {\n /** One or more data directories or `.jsonl` files */\n path: string | readonly string[];\n /** Fields to fill. Defaults to each table's primary key: `primaryKey` in its schema file, or `id` */\n fields?: readonly string[];\n /** Directory the `<Table>.schema.{ts,mts,cts}` files are looked up in. Defaults to each file's data directory */\n schemaDir?: string;\n /**\n * Builds the function that computes a table's row values from its schema module. Defaults to the\n * value its validation schema (the `schema` or default export) gives a row, after its backward\n * transformation; a row the schema rejects gains nothing. Throwing stops the fill before any file\n * is written.\n */\n loadFiller?: (schemaModule: Record<string, unknown>, context: { tableName: string; schemaPath: string }) => RowFiller;\n}\n\nexport interface FilledFile {\n /** Name of the table, matching the JSONL file name */\n table: string;\n file: string;\n /** The fields written into at least one of its rows */\n fields: string[];\n /** How many rows gained a value */\n count: number;\n}\n\nexport interface FillFieldsResult {\n filled: FilledFile[];\n /** Tables without a schema file, so nothing could compute their values */\n tablesWithoutSchema: string[];\n /** The 1-based lines of each file that are not JSON objects, so nothing was filled in there */\n unreadableLines: Array<{ file: string; lines: number[] }>;\n /** Fields to fill that no row of any table got a value for */\n unproducedFields: string[];\n}\n\n/** A JSONL line, kept as text so a line that gains nothing is written back verbatim */\ninterface Line {\n text: string;\n /** The separator after the line, kept so CRLF survives */\n eol: string;\n row: JsonObject | undefined;\n}\n\n/**\n * Fill the named fields into the rows of the JSONL files that have no value for them, with the values\n * each table computes for a row. A value already in the file is never replaced, and a line that gains\n * nothing is left byte for byte; a line that does gain a value is written with its keys in the order\n * the computed row lists them. Every value is computed before any file is written.\n */\nexport async function fillFields(options: FillFieldsOptions): Promise<Result<FillFieldsResult, Error>> {\n try {\n return ok(await fillFieldsInternal(options));\n } catch (error) {\n return err(toError(error));\n }\n}\n\nasync function fillFieldsInternal(options: FillFieldsOptions): Promise<FillFieldsResult> {\n if (options.fields && options.fields.length === 0) {\n throw new Error('No fields to fill. Name at least one field.');\n }\n const paths = typeof options.path === 'string' ? [options.path] : options.path;\n if (paths.length === 0) throw new Error('No paths to fill. Name at least one path.');\n const sources = new Map<string, { table: string; file: string; target: string; schemaDir: string }>();\n for (const path of paths) {\n const { dataDir, tableNames } = await resolveTables(path);\n for (const table of tableNames) {\n const file = join(dataDir, `${table}.jsonl`);\n const key = await realpath(file);\n if (!sources.has(key)) sources.set(key, { table, file, target: key, schemaDir: options.schemaDir ?? dataDir });\n }\n }\n const loadFiller = options.loadFiller ?? fillerFromValidationSchema;\n\n const tablesWithoutSchema: string[] = [];\n const tables: Array<{ table: string; file: string; target: string; fields: readonly string[]; fill: RowFiller }> = [];\n const imports = createSchemaImports();\n for (const { table, file, target, schemaDir } of sources.values()) {\n const schemaPath = await findSchemaFile(schemaDir, table);\n if (!schemaPath) {\n if (!tablesWithoutSchema.includes(table)) tablesWithoutSchema.push(table);\n continue;\n }\n const schemaModule = await imports.import(schemaPath);\n tables.push({\n table,\n file,\n target,\n fields: options.fields ?? [primaryKeyOf(schemaModule)],\n fill: loadFiller(schemaModule, { tableName: table, schemaPath }),\n });\n }\n\n const produced = new Set<string>();\n const unreadableLines: FillFieldsResult['unreadableLines'] = [];\n const filled: FilledFile[] = [];\n const writes: Array<{ file: string; target: string; read: string; content: string }> = [];\n for (const { table, file, target, fields, fill } of tables) {\n const read = await readFile(target, 'utf-8');\n const bom = read.startsWith('\\u{feff}') ? '\\u{feff}' : '';\n const lines = splitLines(read.slice(bom.length));\n const written = new Set<string>();\n const unreadable: number[] = [];\n let count = 0;\n\n lines.forEach((line, index) => {\n if (!line.row) {\n if (line.text.trim() !== '') unreadable.push(index + 1);\n return;\n }\n const computed = fill(structuredClone(line.row));\n const gained = fields.filter((field) => {\n if (isBlank(ownValue(computed, field))) return false;\n produced.add(field);\n // Not judged by isBlank: a value the line holds, even {}, is one the file already has\n return ownValue(line.row!, field) === undefined || ownValue(line.row!, field) === null;\n });\n if (gained.length === 0) return;\n for (const field of gained) {\n setField(line.row, field, computed[field] as JsonValue);\n written.add(field);\n }\n line.text = serializeRow(line.row, Object.keys(computed));\n count += 1;\n });\n\n if (unreadable.length > 0) unreadableLines.push({ file, lines: unreadable });\n if (count === 0) continue;\n writes.push({ file, target, read, content: bom + lines.map((line) => `${line.text}${line.eol}`).join('') });\n filled.push({ table, file, fields: [...written], count });\n }\n\n // Not checking each file as it is written: a change found in a later file would leave the earlier\n // ones already filled\n for (const { file, target, read } of writes) {\n if ((await readFile(target, 'utf-8')) !== read) {\n const error = new Error(\n `JSONL file '${file}' was changed after it was read, so no file was filled. Run the fill again.`,\n ) as JsonlConflictError;\n error.name = 'JsonlConflictError';\n error.file = file;\n throw error;\n }\n }\n await replaceAll(writes);\n\n const named = options.fields ?? [...new Set(tables.flatMap(({ fields }) => fields))];\n return {\n filled,\n tablesWithoutSchema,\n unreadableLines,\n unproducedFields: sources.size > 0 ? named.filter((field) => !produced.has(field)) : [],\n };\n}\n\n/**\n * Write every file or none: each content goes to a temporary file first, the temporaries replace the\n * files once all are written, and the files already replaced are put back when a later one fails\n */\nasync function replaceAll(\n writes: Array<{ file: string; target: string; read: string; content: string }>,\n): Promise<void> {\n const staged = writes.map((write) => ({\n ...write,\n temporary: `${write.target}.${randomBytes(6).toString('hex')}.tmp`,\n }));\n const replaced: typeof staged = [];\n try {\n for (const { target, temporary, content } of staged) {\n await writeFile(temporary, content, 'utf-8');\n // Not left to the umask: the file replaced would otherwise lose a mode such as 0600\n await chmod(temporary, (await stat(target)).mode & 0o7777);\n }\n for (const write of staged) {\n await rename(write.temporary, write.target);\n replaced.push(write);\n }\n } catch (error) {\n const notRestored: string[] = [];\n for (const { file, target, read } of replaced) {\n await writeFile(target, read, 'utf-8').catch(() => notRestored.push(file));\n }\n await Promise.all(staged.map(({ temporary }) => rm(temporary, { force: true })));\n if (notRestored.length === 0) throw error;\n throw new Error(\n `${toError(error).message}\\nThese files could not be put back and stay filled: ${notRestored.join(', ')}`,\n { cause: error },\n );\n }\n}\n\nasync function resolveTables(path: string): Promise<{ dataDir: string; tableNames: string[] }> {\n const stats = await stat(path);\n if (stats.isDirectory()) {\n const entries = await readdir(path);\n const tableNames = entries\n .filter((entry) => entry.endsWith('.jsonl'))\n .map((entry) => basename(entry, '.jsonl'))\n .sort();\n return { dataDir: path, tableNames };\n }\n if (stats.isFile() && path.endsWith('.jsonl')) {\n return { dataDir: dirname(path), tableNames: [basename(path, '.jsonl')] };\n }\n throw new Error(`Invalid path: ${path}. Must be a directory or .jsonl file.`);\n}\n\nfunction primaryKeyOf(schemaModule: Record<string, unknown>): string {\n const schema = (schemaModule.schema ?? schemaModule.default) as { primaryKey?: unknown } | undefined;\n const primaryKey = schema?.primaryKey ?? schemaModule.primaryKey;\n return typeof primaryKey === 'string' ? primaryKey : 'id';\n}\n\nfunction fillerFromValidationSchema(\n schemaModule: Record<string, unknown>,\n { schemaPath }: { schemaPath: string },\n): RowFiller {\n const schema = (schemaModule.schema ?? schemaModule.default) as StandardSchema | undefined;\n if (!schema || typeof schema !== 'object' || !('~standard' in schema)) {\n throw new Error(`${schemaPath} does not export a StandardSchema as \\`schema\\` or as its default export`);\n }\n return (row) => {\n const result = schema['~standard'].validate(row);\n if (result instanceof Promise) {\n throw new Error(`${schemaPath}: asynchronous validation is not supported`);\n }\n if (result.issues) return {};\n return hasBackward(schema)\n ? ((schema as BiDirectionalSchema<Table, Table>).backward!(result.value) as Record<string, unknown>)\n : result.value;\n };\n}\n\nfunction ownValue(row: Record<string, unknown>, field: string): unknown {\n return Object.hasOwn(row, field) ? row[field] : undefined;\n}\n\n// Not `row[field] = value`: a field named `__proto__` would go through the inherited setter and leave\n// no own property for the serializer to read back\nfunction setField(row: JsonObject, field: string, value: JsonValue): void {\n Object.defineProperty(row, field, { value, enumerable: true, writable: true, configurable: true });\n}\n\nfunction isBlank(value: unknown): boolean {\n if (value === undefined || value === null) return true;\n if (typeof value !== 'object' || Array.isArray(value)) return false;\n // A nested field the row never had can come back as an object of blank values, which fills nothing in\n return Object.values(value).every(isBlank);\n}\n\nfunction splitLines(content: string): Line[] {\n if (content === '') return [];\n return content.split('\\n').map((raw, index, all) => {\n const carriage = raw.endsWith('\\r') ? '\\r' : '';\n const text = carriage ? raw.slice(0, -1) : raw;\n let row: JsonObject | undefined;\n if (text.trim() !== '') {\n try {\n const parsed: unknown = JSON.parse(text);\n row =\n parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? (parsed as JsonObject) : undefined;\n } catch {\n row = undefined;\n }\n }\n return { text, eol: index === all.length - 1 ? carriage : `${carriage}\\n`, row };\n });\n}\n\n/** The row with its keys in the order the computed row lists them, and keys it does not list after those */\nfunction serializeRow(row: JsonObject, fieldOrder: string[]): string {\n const rank = new Map(fieldOrder.map((field, index) => [field, index]));\n const rankOf = (key: string): number => rank.get(key) ?? fieldOrder.length;\n const ordered = Object.entries(row).sort(([a], [b]) => rankOf(a) - rankOf(b));\n const out: JsonObject = {};\n for (const [key, value] of ordered) setField(out, key, value);\n return JSON.stringify(out);\n}\n","import { readdir } from 'node:fs/promises';\nimport { join, relative, basename, dirname, isAbsolute } from 'node:path';\nimport { writeFile, mkdir } from 'node:fs/promises';\nimport { findSchemaFileInEntries, rewriteExtensionForImport } from './schema-extensions.js';\n\nexport interface TypeGeneratorOptions {\n dataDir: string;\n projectRoot?: string; // Default: current working directory\n output?: string; // Output file path (default: db.ts in dataDir)\n}\n\ninterface TableInfo {\n tableName: string;\n schemaFile?: string;\n}\n\nexport class TypeGenerator {\n private dataDir: string;\n private projectRoot: string;\n private outputFile: string;\n private dataDirPath: string;\n\n constructor(options: TypeGeneratorOptions) {\n // For testing: allow overriding projectRoot via environment variable\n const envProjectRoot = process.env.LINES_DB_TEST_PROJECT_ROOT;\n this.projectRoot = envProjectRoot !== undefined ? envProjectRoot : options.projectRoot || process.cwd();\n this.dataDir = options.dataDir;\n this.dataDirPath = isAbsolute(this.dataDir) ? this.dataDir : join(this.projectRoot, this.dataDir);\n this.outputFile = options.output\n ? isAbsolute(options.output)\n ? options.output\n : join(this.projectRoot, options.output)\n : join(this.dataDirPath, 'db.ts');\n }\n\n /**\n * Generate types file from JSONL files and their optional schema files.\n */\n async generate(): Promise<string> {\n // Find all JSONL files and their corresponding schema files\n const tables = await this.findTables();\n\n if (tables.length === 0) {\n throw new Error(`No JSONL files found in ${this.dataDirPath}. Place one or more *.jsonl files in the directory.`);\n }\n\n // Generate type declarations\n const content = this.generateTypeDeclarations(tables);\n\n // Ensure output directory exists\n const outputDir = dirname(this.outputFile);\n await mkdir(outputDir, { recursive: true });\n\n // Write to file\n await writeFile(this.outputFile, content, 'utf-8');\n console.log(`Generated types at ${this.outputFile}`);\n return this.outputFile;\n }\n\n /**\n * Find all *.jsonl files and check if they have corresponding *.schema.ts files\n */\n private async findTables(): Promise<TableInfo[]> {\n try {\n const entries = await readdir(this.dataDirPath, { withFileTypes: true });\n const tables: TableInfo[] = [];\n\n for (const entry of entries) {\n if (entry.isFile() && entry.name.endsWith('.jsonl')) {\n const tableName = basename(entry.name, '.jsonl');\n const schemaFilePath = findSchemaFileInEntries(this.dataDirPath, tableName, entries);\n\n tables.push({\n tableName,\n schemaFile: schemaFilePath,\n });\n }\n }\n\n return tables;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new Error(`Data directory not found: ${this.dataDirPath}. Set lines-db.dataDir to the correct location.`);\n }\n throw error;\n }\n }\n\n /**\n * Generate type declaration content\n */\n private generateTypeDeclarations(tables: TableInfo[]): string {\n const imports: string[] = [];\n const tableEntries: string[] = [];\n const usedAliases = new Set<string>();\n\n for (const table of tables) {\n const tableKey = this.formatTableKey(table.tableName);\n\n if (table.schemaFile) {\n // Table has a schema file\n const schemaIdentifier = this.createSchemaIdentifier(table.tableName, usedAliases);\n usedAliases.add(schemaIdentifier);\n\n // Calculate relative path from output file to schema file\n let relativePath = rewriteExtensionForImport(\n relative(join(this.outputFile, '..'), table.schemaFile).replace(/\\\\/g, '/'), // Convert Windows paths to Unix-style\n );\n\n // Ensure relative path starts with './' or '../'\n if (!relativePath.startsWith('.')) {\n relativePath = './' + relativePath;\n }\n\n // Add import statement for schema\n imports.push(`import { schema as ${schemaIdentifier} } from '${relativePath}';`);\n\n // Add table entry with InferOutput\n tableEntries.push(` ${tableKey}: InferOutput<typeof ${schemaIdentifier}>;`);\n } else {\n // Table has no schema file, use Record<string, unknown>\n tableEntries.push(` ${tableKey}: Record<string, unknown>;`);\n }\n }\n\n // Generate full content\n const importSection = imports.length > 0 ? `${imports.join('\\n')}\\n` : '';\n const inferOutputImport = imports.length > 0 ? ', InferOutput' : '';\n\n return `// Auto-generated by lines-db\n// Do not edit this file manually\n\n${importSection}import type { DatabaseConfig${inferOutputImport} } from 'lines-db';\nimport { fileURLToPath } from 'node:url';\nimport { dirname } from 'node:path';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\nexport type Tables = {\n${tableEntries.join('\\n')}\n};\n\nexport const config: DatabaseConfig<Tables> = {\n dataDir: __dirname,\n};\n`;\n }\n\n private createSchemaIdentifier(tableName: string, usedAliases: Set<string>): string {\n const camel = toCamelCase(tableName);\n const sanitizedBase = sanitizeIdentifier(camel);\n let base = sanitizedBase || 'table';\n\n if (!/^[A-Za-z_$]/.test(base)) {\n base = `_${base}`;\n }\n\n let candidate = `${base}Schema`;\n let suffix = 1;\n while (usedAliases.has(candidate)) {\n candidate = `${base}${++suffix}Schema`;\n }\n\n return candidate;\n }\n\n private formatTableKey(tableName: string): string {\n const identifierPattern = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n if (identifierPattern.test(tableName)) {\n return tableName;\n }\n const escaped = tableName.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\");\n return `'${escaped}'`;\n }\n}\n\nfunction toCamelCase(value: string): string {\n const parts = value\n .split(/[^A-Za-z0-9]+/)\n .filter(Boolean)\n .map((part) => part.toLowerCase());\n\n if (parts.length === 0) {\n return value;\n }\n\n const [first, ...rest] = parts;\n return first + rest.map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join('');\n}\n\nfunction sanitizeIdentifier(value: string): string {\n return value.replace(/[^A-Za-z0-9_$]/g, '');\n}\n","import { join } from 'node:path';\nimport type { JsonObject } from './types.js';\nimport { JsonlReader } from './jsonl-reader.js';\nimport { LinesDB } from './database.js';\nimport { unwrap } from './result.js';\n\nexport interface TableValidationOptions {\n dataDir: string;\n tableName: string;\n rows: JsonObject[];\n}\n\n/**\n * Validate a table by temporarily supplying in-memory rows while reusing the existing LinesDB validation pipeline.\n * If validation fails, throws an error with validation details.\n */\nexport async function ensureTableRowsValid(options: TableValidationOptions): Promise<void> {\n const tablePath = join(options.dataDir, `${options.tableName}.jsonl`);\n const overrides = new Map<string, JsonObject[]>([[tablePath, options.rows]]);\n\n await JsonlReader.withOverrides(overrides, async () => {\n const db = LinesDB.create({ dataDir: options.dataDir });\n try {\n // Initialize only the target table\n const result = unwrap(await db.initialize({ tableName: options.tableName }));\n\n // If validation failed, throw an error with details\n if (!result.valid) {\n const errorCount = result.errors.length;\n const errorDetails = result.errors\n .map((e) => {\n const issueMessages = e.issues.map((issue) => issue.message).join(', ');\n return ` Row ${e.rowIndex}: ${issueMessages}`;\n })\n .join('\\n');\n\n throw new Error(\n `Validation failed for table '${options.tableName}' (${errorCount} error(s)):\\n${errorDetails}`,\n );\n }\n } finally {\n await db.close();\n }\n });\n}\n","import type { StandardSchemaIssue } from './types.js';\nimport { styleText } from 'node:util';\n\nexport interface ValidationErrorInfo {\n file: string;\n rowIndex: number;\n issues: ReadonlyArray<StandardSchemaIssue>;\n data?: unknown;\n originalData?: unknown;\n}\n\nexport interface ForeignKeyErrorInfo {\n file: string;\n rowIndex: number;\n column: string;\n value: unknown;\n referencedTable: string;\n referencedColumn: string;\n data?: unknown;\n}\n\nexport interface ErrorFormatterOptions {\n verbose?: boolean;\n}\n\nexport class ErrorFormatter {\n private verbose: boolean;\n\n constructor(options: ErrorFormatterOptions = {}) {\n this.verbose = options.verbose ?? false;\n }\n\n /**\n * Format validation errors\n */\n formatValidationErrors(errors: ValidationErrorInfo[]): string {\n if (this.verbose) {\n return this.formatValidationErrorsVerbose(errors);\n }\n return this.formatValidationErrorsCompact(errors);\n }\n\n /**\n * Format foreign key error\n */\n formatForeignKeyError(error: ForeignKeyErrorInfo): string {\n if (this.verbose) {\n return this.formatForeignKeyErrorVerbose(error);\n }\n return this.formatForeignKeyErrorCompact(error);\n }\n\n /**\n * Format compact (default) validation errors\n */\n private formatValidationErrorsCompact(errors: ValidationErrorInfo[]): string {\n const lines: string[] = [];\n\n for (const error of errors) {\n for (const issue of error.issues) {\n const fieldPath = this.getFieldPath(issue);\n const line = `${error.file}:${error.rowIndex + 1} • ${fieldPath}: ${issue.message}`;\n lines.push(line);\n }\n }\n\n return lines.join('\\n');\n }\n\n /**\n * Format verbose validation errors\n */\n private formatValidationErrorsVerbose(errors: ValidationErrorInfo[]): string {\n const blocks: string[] = [];\n\n for (let i = 0; i < errors.length; i++) {\n const error = errors[i];\n const isLast = i === errors.length - 1;\n const prefix = isLast ? '└─' : '├─';\n const linePrefix = isLast ? ' ' : '│ ';\n\n const lines: string[] = [`${prefix} ${error.file}:${error.rowIndex + 1}`];\n\n for (const issue of error.issues) {\n const fieldPath = this.getFieldPath(issue);\n lines.push(`${linePrefix}Field: ${fieldPath}`);\n lines.push(`${linePrefix}Error: ${issue.message}`);\n }\n\n // Show original data if available (migrate case)\n if (error.originalData !== undefined) {\n lines.push(`${linePrefix}Original data: ${JSON.stringify(error.originalData)}`);\n }\n\n // Show data\n if (error.data !== undefined) {\n const label = error.originalData !== undefined ? 'Transformed data' : 'Data';\n lines.push(`${linePrefix}${label}: ${JSON.stringify(error.data)}`);\n }\n\n blocks.push(lines.join('\\n'));\n }\n\n return blocks.join('\\n│\\n');\n }\n\n /**\n * Format compact foreign key error\n */\n private formatForeignKeyErrorCompact(error: ForeignKeyErrorInfo): string {\n 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})`;\n }\n\n /**\n * Format verbose foreign key error\n */\n private formatForeignKeyErrorVerbose(error: ForeignKeyErrorInfo): string {\n const lines: string[] = [\n `└─ ${error.file}:${error.rowIndex + 1}`,\n ` Type: Foreign Key Violation`,\n ` Field: ${error.column}`,\n ` Value: ${JSON.stringify(error.value)}`,\n ` References: ${error.referencedTable}(${error.referencedColumn})`,\n ` Error: Referenced value does not exist in target table`,\n ];\n\n if (error.data !== undefined) {\n lines.push(` Data: ${JSON.stringify(error.data)}`);\n }\n\n return lines.join('\\n');\n }\n\n /**\n * Get field path from issue\n */\n private getFieldPath(issue: StandardSchemaIssue): string {\n if (!issue.path || issue.path.length === 0) {\n return 'root';\n }\n\n return issue.path\n .map((segment) => {\n if (typeof segment === 'object' && segment !== null && 'key' in segment) {\n return String(segment.key);\n }\n return String(segment);\n })\n .join('.');\n }\n\n /**\n * Format error header with count\n */\n formatErrorHeader(count: number, file?: string): string {\n const fileInfo = file ? ` in ${file}` : '';\n return styleText('red', `✗ Found ${count} error(s)${fileInfo}`);\n }\n\n /**\n * Format migration failure header\n */\n formatMigrationFailureHeader(): string {\n return styleText('red', '\\n✗ Migration failed and was rolled back');\n }\n}\n","import { readFile, realpath, stat } from 'node:fs/promises';\nimport { basename, dirname, resolve } from 'node:path';\nimport { z } from 'zod';\nimport type { DatabaseConfig } from './types.js';\n\nconst directories = z.array(z.string().min(1)).min(1);\nconst datasetConfigSchema = z.strictObject({\n schemaDir: z.string().min(1),\n base: directories,\n datasets: z.record(z.string().min(1), directories),\n});\n\ninterface ValidationOptions {\n path?: string;\n config?: string;\n dataset?: string[];\n allDatasets?: boolean;\n}\n\nexport async function resolveValidationTarget(\n options: ValidationOptions,\n): Promise<DatabaseConfig & { tableName?: string }> {\n if (options.dataset !== undefined && options.allDatasets) {\n throw new Error('Use either --dataset or --all-datasets, not both.');\n }\n if (options.path !== undefined) {\n if (options.config !== undefined || options.dataset !== undefined || options.allDatasets) {\n throw new Error('A file or directory path cannot be combined with dataset configuration options.');\n }\n const stats = await stat(options.path);\n if (stats.isDirectory()) return { dataDir: options.path };\n if (stats.isFile() && options.path.endsWith('.jsonl')) {\n return { dataDir: dirname(options.path), tableName: basename(options.path, '.jsonl') };\n }\n throw new Error(`Invalid path: ${options.path}. Must be a directory or .jsonl file.`);\n }\n\n return loadDatasetConfig(options.config, {\n datasets: options.allDatasets ? 'all' : options.dataset,\n });\n}\n\nexport interface DatasetConfigOptions {\n datasets?: string[] | 'all';\n}\n\nexport async function loadDatasetConfig(\n path = 'lines-db.config.json',\n options: DatasetConfigOptions = {},\n): Promise<DatabaseConfig> {\n const configPath = resolve(path);\n let config: z.infer<typeof datasetConfigSchema>;\n try {\n config = datasetConfigSchema.parse(JSON.parse(await readFile(configPath, 'utf-8')));\n } catch (error) {\n throw new Error(\n `Failed to load dataset configuration ${configPath}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n\n const names = options.datasets === 'all' ? Object.keys(config.datasets) : (options.datasets ?? []);\n const selected = names.flatMap((name) => {\n if (!Object.hasOwn(config.datasets, name)) {\n throw new Error(\n `Unknown dataset '${name}'. Available datasets: ${Object.keys(config.datasets).join(', ') || '(none)'}`,\n );\n }\n return config.datasets[name];\n });\n\n const configDir = dirname(configPath);\n const schemaDir = resolve(configDir, config.schemaDir);\n try {\n if (!(await stat(schemaDir)).isDirectory()) throw new Error('Expected a directory');\n } catch (error) {\n throw new Error(`Invalid schemaDir ${schemaDir}: ${error instanceof Error ? error.message : String(error)}`);\n }\n const dataDirs = await Promise.all([...config.base, ...selected].map((dir) => realpath(resolve(configDir, dir))));\n return {\n dataDir: [...new Set(dataDirs)],\n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