lines-db 0.0.0-stage → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,6 @@
1
+ import { r as hashJsonlContent } from "./jsonl-reader-CoYEJ9pg.mjs";
2
+ //#region src/replace-file.d.ts
3
+ export declare function replaceFile(file: string, write: ((temporary: string) => Promise<void>) | undefined, expected: string | undefined): Promise<void>;
4
+ //#endregion
5
+ export { hashJsonlContent };
6
+ //# sourceMappingURL=internal.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"internal.d.mts","names":[],"sources":["../src/replace-file.ts"],"mappings":";;wBAIsB,YACpB,cACA,SAAS,sBAAsB,4BAC/B,+BACC"}
@@ -0,0 +1 @@
1
+ export { r as hashJsonlContent, t as replaceFile } from "./replace-file-AWLIm7aN.mjs";
@@ -0,0 +1,186 @@
1
+ import { StandardSchemaV1 } from "@standard-schema/spec";
2
+ //#region src/types.d.ts
3
+ type Table = Record<string, unknown>;
4
+ type StandardSchema<Input extends Table = Table, Output extends Table = Input> = StandardSchemaV1<Input, Output>;
5
+ type StandardSchemaResult<Output> = StandardSchemaV1.Result<Output>;
6
+ type StandardSchemaIssue = StandardSchemaV1.Issue;
7
+ type InferInput<T> = T extends StandardSchemaV1<infer I, unknown> ? I : never;
8
+ type InferOutput<T> = T extends StandardSchemaV1<unknown, infer O> ? O : never;
9
+ interface TableValidationResult {
10
+ tableName: string;
11
+ valid: boolean;
12
+ rowCount: number;
13
+ errors: ValidationErrorDetail[];
14
+ warnings: string[];
15
+ }
16
+ interface ValidationResult {
17
+ valid: boolean;
18
+ errors: ValidationErrorDetail[];
19
+ warnings: string[];
20
+ tableResults: TableValidationResult[];
21
+ }
22
+ interface ValidationErrorDetail {
23
+ file: string;
24
+ tableName: string;
25
+ rowIndex: number;
26
+ issues: ReadonlyArray<StandardSchemaIssue>;
27
+ type?: 'schema' | 'foreignKey';
28
+ foreignKeyError?: {
29
+ column: string;
30
+ value: unknown;
31
+ referencedTable: string;
32
+ referencedColumn: string;
33
+ };
34
+ }
35
+ interface ForeignKeyDefinition {
36
+ column: string;
37
+ references: {
38
+ table: string;
39
+ column: string;
40
+ };
41
+ onDelete?: 'CASCADE' | 'SET NULL' | 'RESTRICT' | 'NO ACTION';
42
+ onUpdate?: 'CASCADE' | 'SET NULL' | 'RESTRICT' | 'NO ACTION';
43
+ }
44
+ interface IndexDefinition {
45
+ name?: string;
46
+ columns: string[];
47
+ unique?: boolean;
48
+ }
49
+ interface TableSchema {
50
+ name: string;
51
+ columns: ColumnDefinition[];
52
+ foreignKeys?: ForeignKeyDefinition[];
53
+ /** The foreign keys the schema file declares, including those left out of `foreignKeys` because the table they reference failed to load */
54
+ declaredForeignKeys?: ForeignKeyDefinition[];
55
+ indexes?: IndexDefinition[];
56
+ }
57
+ interface ColumnDefinition {
58
+ name: string;
59
+ type: 'TEXT' | 'INTEGER' | 'REAL' | 'BLOB' | 'NULL' | 'JSON';
60
+ primaryKey?: boolean;
61
+ notNull?: boolean;
62
+ unique?: boolean;
63
+ valueType?: 'boolean';
64
+ }
65
+ type TableDefs = Record<string, Table>;
66
+ declare const TABLES_BRAND: unique symbol;
67
+ interface DatabaseConfig<_Tables extends TableDefs = TableDefs> {
68
+ /**
69
+ * Directory containing JSONL files, or several directories whose files are read as one set of
70
+ * tables: a table found in more than one of them has the rows of each file, in this order.
71
+ */
72
+ dataDir: string | readonly string[];
73
+ /**
74
+ * Directory the `<Table>.schema.{ts,mts,cts}` files are looked up in, for validation and for
75
+ * discovering foreign keys. Defaults to the directory of each table's JSONL file.
76
+ */
77
+ schemaDir?: string;
78
+ writeDataSets?: boolean;
79
+ /**
80
+ * Fields written back to the JSONL files on sync.
81
+ * When set, only these fields are taken from the database; every other field keeps the value
82
+ * its JSONL line already had, so hook-computed values and omitted optional fields are untouched.
83
+ * An empty list takes no field from the database, so existing lines keep every value they hold -
84
+ * rows added to or removed from the database are still reflected.
85
+ * Defaults to writing every field of the row.
86
+ */
87
+ writeBackFields?: readonly string[];
88
+ /**
89
+ * Which of the values a validation schema fills in - defaults and the fields it computes - a
90
+ * write-back writes into the file. `'all'` writes every one. `'primaryKey'` writes only a primary
91
+ * key the schema generated, so a row keeps it, and leaves every other one to the schema: a line then
92
+ * holds the fields it was written with, an insert was given and an update changed.
93
+ * Defaults to `'all'`.
94
+ */
95
+ writeFilledValues?: WriteFilledValues;
96
+ readonly [TABLES_BRAND]?: _Tables;
97
+ }
98
+ /** Which values a validation schema fills in a write-back writes; see {@link DatabaseConfig.writeFilledValues} */
99
+ type WriteFilledValues = 'all' | 'primaryKey';
100
+ interface TableConfig {
101
+ jsonlPath: string;
102
+ /**
103
+ * Every JSONL file the table's rows are read from, concatenated in this order.
104
+ * Defaults to `[jsonlPath]`.
105
+ */
106
+ jsonlPaths?: readonly string[];
107
+ schema?: TableSchema;
108
+ autoInferSchema?: boolean;
109
+ validationSchema?: StandardSchema;
110
+ }
111
+ interface ValidationError extends Error {
112
+ name: 'ValidationError';
113
+ issues: ReadonlyArray<StandardSchemaIssue>;
114
+ }
115
+ interface JsonlParseError extends Error {
116
+ name: 'JsonlParseError';
117
+ file: string;
118
+ line: number;
119
+ }
120
+ interface JsonlConflictError extends Error {
121
+ name: 'JsonlConflictError';
122
+ file: string;
123
+ }
124
+ type JsonValue = string | number | boolean | null | JsonObject | JsonArray;
125
+ interface JsonObject {
126
+ [key: string]: JsonValue;
127
+ }
128
+ type JsonArray = JsonValue[];
129
+ type WhereValue<T> = T | ((value: T) => boolean);
130
+ type WhereObject<T extends Table> = { [K in keyof T]?: WhereValue<T[K]>; };
131
+ type WhereCondition<T extends Table> = WhereObject<T> | WhereConditionArray<T>;
132
+ type WhereConditionArray<T extends Table> = Array<WhereObject<T> | WhereConditionArray<T>>;
133
+ //#endregion
134
+ //#region src/result.d.ts
135
+ /**
136
+ * A discriminated union for operations that can fail without throwing.
137
+ * Used throughout the JS programmatic API (`LinesDB`, `JsonlReader`) so callers get a typed
138
+ * error back instead of having to wrap every call in try/catch.
139
+ */
140
+ type Result<T, E = Error> = {
141
+ ok: true;
142
+ value: T;
143
+ } | {
144
+ ok: false;
145
+ error: E;
146
+ };
147
+ declare function ok<T>(value: T): Result<T, never>;
148
+ declare function err<E>(error: E): Result<never, E>;
149
+ /** Unwrap a Result, throwing its error when it is not ok. */
150
+ declare function unwrap<T, E>(result: Result<T, E>): T;
151
+ //#endregion
152
+ //#region src/jsonl-reader.d.ts
153
+ /** Fingerprint of a JSONL file's content, to tell whether the file changed since it was read */
154
+ declare function hashJsonlContent(content: string): string;
155
+ interface JsonlSnapshot {
156
+ /** The rows the content parses into, or why it does not parse */
157
+ rows: Result<JsonObject[], JsonlParseError>;
158
+ /** Undefined when the rows come from an override rather than the file */
159
+ contentHash: string | undefined;
160
+ }
161
+ declare class JsonlReader {
162
+ private static overrides;
163
+ /**
164
+ * Temporarily override the data returned for specific JSONL files.
165
+ * Useful for scenarios like migration validation where in-memory data should be used.
166
+ */
167
+ static withOverrides<T>(overrides: Map<string, JsonObject[]>, fn: () => Promise<T>): Promise<T>;
168
+ /**
169
+ * Read JSONL file and parse each line as JSON
170
+ */
171
+ static read(filePath: string): Promise<Result<JsonObject[], JsonlParseError | Error>>;
172
+ /**
173
+ * Read JSONL file like {@link read}, along with a hash of the content the rows were parsed from.
174
+ * The hash is there even when the content does not parse.
175
+ */
176
+ static readSnapshot(filePath: string): Promise<Result<JsonlSnapshot, Error>>;
177
+ private static parse;
178
+ /**
179
+ * Infer schema from JSONL data
180
+ */
181
+ static inferSchema(tableName: string, data: JsonObject[]): Result<TableSchema, Error>;
182
+ private static inferType;
183
+ }
184
+ //#endregion
185
+ export { WhereCondition as A, TableConfig as C, ValidationError as D, TableValidationResult as E, ValidationErrorDetail as O, Table as S, TableSchema as T, JsonlConflictError as _, err as a, StandardSchemaIssue as b, ColumnDefinition as c, IndexDefinition as d, InferInput as f, JsonValue as g, JsonObject as h, Result as i, WriteFilledValues as j, ValidationResult as k, DatabaseConfig as l, JsonArray as m, JsonlSnapshot as n, ok as o, InferOutput as p, hashJsonlContent as r, unwrap as s, JsonlReader as t, ForeignKeyDefinition as u, JsonlParseError as v, TableDefs as w, StandardSchemaResult as x, StandardSchema as y };
186
+ //# sourceMappingURL=jsonl-reader-CoYEJ9pg.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jsonl-reader-CoYEJ9pg.d.mts","names":[],"sources":["../src/types.ts","../src/result.ts","../src/jsonl-reader.ts"],"mappings":";;KAGY,QAAQ;KACR,eAAe,cAAc,QAAQ,OAAO,eAAe,QAAQ,SAAS,iBAAiB,OAAO;KACpG,qBAAqB,UAAU,iBAAiB,OAAO;KACvD,sBAAsB,iBAAiB;KAOvC,WAAW,KAAK,UAAU,uBAAuB,cAAc;KAC/D,YAAY,KAAK,UAAU,gCAAgC,KAAK;UAG3D;EACf;EACA;EACA;EACA,QAAQ;EACR;;UAGe;EACf;EACA,QAAQ;EACR;EACA,cAAc;;UAGC;EACf;EACA;EACA;EACA,QAAQ,cAAc;EACtB;EACA;IACE;IACA;IACA;IACA;;;UAIa;EACf;EACA;IACE;IACA;;EAEF;EACA;;UAGe;EACf;EACA;EACA;;UAGe;EACf;EACA,SAAS;EACT,cAAc;;EAEd,sBAAsB;EACtB,UAAU;;UAGK;EACf;EACA;EACA;EACA;EACA;EACA;;KAGU,YAAY,eAAe;cAClB;UAEJ,eAAe,gBAAgB,YAAY;;;;;EAK1D;;;;;EAKA;EACA;;;;;;;;;EASA;;;;;;;;EAQA,oBAAoB;YACV,gBAAgB;;;KAIhB;UAYK;EACf;;;;;EAKA;EACA,SAAS;EACT;EACA,mBAAmB;;UAGJ,wBAAwB;EACvC;EACA,QAAQ,cAAc;;UAGP,wBAAwB;EACvC;EACA;EACA;;UAGe,2BAA2B;EAC1C;EACA;;KAGU,+CAA+C,aAAa;UACvD;GACd,cAAc;;KAEL,YAAY;KAGZ,WAAW,KAAK,MAAM,OAAO;KAE7B,YAAY,UAAU,YAC/B,WAAW,KAAK,WAAW,EAAE;KAGpB,eAAe,UAAU,SACjC,YAAY,KACZ,oBAAoB;KAEZ,oBAAoB,UAAU,SAAS,MAAM,YAAY,KAAK,oBAAoB;;;;;;;;KCxKlF,OAAO,GAAG,IAAI;EAAW;EAAU,OAAO;;EAAQ;EAAW,OAAO;;iBAEhE,GAAG,GAAG,OAAO,IAAI,OAAO;iBAIxB,IAAI,GAAG,OAAO,IAAI,cAAc;;iBAUhC,OAAO,GAAG,GAAG,QAAQ,OAAO,GAAG,KAAK;;;;iBCdpC,iBAAiB;UAIhB;;EAEf,MAAM,OAAO,cAAc;;EAE3B;;cAGW;iBACI;;;;;SAMF,cAAc,GAAG,WAAW,YAAY,eAAe,UAAU,QAAQ,KAAK,QAAQ;;;;SAmBtF,KAAK,mBAAmB,QAAQ,OAAO,cAAc,kBAAkB;;;;;SASvE,aAAa,mBAAmB,QAAQ,OAAO,eAAe;iBAoB5D;;;;SAiCR,YAAY,mBAAmB,MAAM,eAAe,OAAO,aAAa;iBAsEhE"}
@@ -0,0 +1,203 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { chmod, link, readFile, rename, rm, stat } from "node:fs/promises";
3
+ import { normalize } from "node:path";
4
+ //#region src/result.ts
5
+ function ok(value) {
6
+ return {
7
+ ok: true,
8
+ value
9
+ };
10
+ }
11
+ function err(error) {
12
+ return {
13
+ ok: false,
14
+ error
15
+ };
16
+ }
17
+ /** Normalize a thrown value (which may not be an Error) into an Error. */
18
+ function toError(value) {
19
+ return value instanceof Error ? value : new Error(String(value));
20
+ }
21
+ /** Unwrap a Result, throwing its error when it is not ok. */
22
+ function unwrap(result) {
23
+ if (result.ok) return result.value;
24
+ throw result.error;
25
+ }
26
+ //#endregion
27
+ //#region src/jsonl-reader.ts
28
+ /** Fingerprint of a JSONL file's content, to tell whether the file changed since it was read */
29
+ function hashJsonlContent(content) {
30
+ return createHash("sha256").update(content).digest("hex");
31
+ }
32
+ var JsonlReader = class {
33
+ static overrides = null;
34
+ /**
35
+ * Temporarily override the data returned for specific JSONL files.
36
+ * Useful for scenarios like migration validation where in-memory data should be used.
37
+ */
38
+ static async withOverrides(overrides, fn) {
39
+ const normalized = /* @__PURE__ */ new Map();
40
+ for (const [filePath, rows] of overrides) normalized.set(normalize(filePath), rows);
41
+ const previousOverrides = this.overrides;
42
+ this.overrides = normalized;
43
+ try {
44
+ return await fn();
45
+ } finally {
46
+ this.overrides = previousOverrides;
47
+ }
48
+ }
49
+ /**
50
+ * Read JSONL file and parse each line as JSON
51
+ */
52
+ static async read(filePath) {
53
+ const result = await this.readSnapshot(filePath);
54
+ return result.ok ? result.value.rows : result;
55
+ }
56
+ /**
57
+ * Read JSONL file like {@link read}, along with a hash of the content the rows were parsed from.
58
+ * The hash is there even when the content does not parse.
59
+ */
60
+ static async readSnapshot(filePath) {
61
+ const overrideRows = this.overrides?.get(normalize(filePath));
62
+ if (overrideRows) return ok({
63
+ rows: ok(overrideRows.map((row) => JSON.parse(JSON.stringify(row)))),
64
+ contentHash: void 0
65
+ });
66
+ let content;
67
+ try {
68
+ content = await readFile(filePath, "utf-8");
69
+ } catch (error) {
70
+ return err(toError(error));
71
+ }
72
+ return ok({
73
+ rows: this.parse(filePath, content),
74
+ contentHash: hashJsonlContent(content)
75
+ });
76
+ }
77
+ static parse(filePath, content) {
78
+ const rawLines = (content.startsWith("") ? content.slice(1) : content).split("\n");
79
+ const rows = [];
80
+ for (let i = 0; i < rawLines.length; i++) {
81
+ const line = rawLines[i].endsWith("\r") ? rawLines[i].slice(0, -1) : rawLines[i];
82
+ if (line.trim().length === 0) continue;
83
+ const fail = (message, cause) => {
84
+ const parseError = new Error(message, { cause });
85
+ parseError.name = "JsonlParseError";
86
+ parseError.file = filePath;
87
+ parseError.line = i + 1;
88
+ return err(parseError);
89
+ };
90
+ let value;
91
+ try {
92
+ value = JSON.parse(line);
93
+ } catch (error) {
94
+ return fail(`Failed to parse JSON line: ${line}`, error);
95
+ }
96
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return fail(`A JSONL line holds a row, which is a JSON object: ${line}`);
97
+ rows.push(value);
98
+ }
99
+ return ok(rows);
100
+ }
101
+ /**
102
+ * Infer schema from JSONL data
103
+ */
104
+ static inferSchema(tableName, data) {
105
+ if (data.length === 0) return err(/* @__PURE__ */ new Error("Cannot infer schema from empty data"));
106
+ const columnTypes = /* @__PURE__ */ new Map();
107
+ const presence = /* @__PURE__ */ new Map();
108
+ const booleanColumns = /* @__PURE__ */ new Set();
109
+ const nonBooleanColumns = /* @__PURE__ */ new Set();
110
+ for (const row of data) for (const [key, value] of Object.entries(row)) {
111
+ if (!columnTypes.has(key)) columnTypes.set(key, /* @__PURE__ */ new Set());
112
+ columnTypes.get(key).add(this.inferType(value));
113
+ presence.set(key, (presence.get(key) ?? 0) + 1);
114
+ if (typeof value === "boolean") booleanColumns.add(key);
115
+ else if (value !== null) nonBooleanColumns.add(key);
116
+ }
117
+ const columns = [];
118
+ for (const [columnName, types] of columnTypes.entries()) {
119
+ const typeArray = Array.from(types);
120
+ let sqlType = "TEXT";
121
+ if (typeArray.length === 1) sqlType = typeArray[0];
122
+ else if (typeArray.every((t) => t === "INTEGER" || t === "REAL")) sqlType = "REAL";
123
+ else if (!typeArray.includes("NULL")) sqlType = "TEXT";
124
+ else if (typeArray.length === 2 && typeArray.includes("NULL")) sqlType = typeArray.find((t) => t !== "NULL");
125
+ const isBooleanColumn = booleanColumns.has(columnName) && !nonBooleanColumns.has(columnName);
126
+ columns.push({
127
+ name: columnName,
128
+ type: sqlType,
129
+ notNull: !typeArray.includes("NULL") && presence.get(columnName) === data.length,
130
+ valueType: isBooleanColumn ? "boolean" : void 0
131
+ });
132
+ }
133
+ const idColumn = columns.find((col) => col.name === "id");
134
+ if (idColumn) idColumn.primaryKey = true;
135
+ return ok({
136
+ name: tableName,
137
+ columns
138
+ });
139
+ }
140
+ static inferType(value) {
141
+ if (value === null || value === void 0) return "NULL";
142
+ if (typeof value === "number") return Number.isInteger(value) ? "INTEGER" : "REAL";
143
+ if (typeof value === "string") return "TEXT";
144
+ if (typeof value === "boolean") return "INTEGER";
145
+ if (typeof value === "object") return "JSON";
146
+ return "TEXT";
147
+ }
148
+ };
149
+ //#endregion
150
+ //#region src/replace-file.ts
151
+ async function replaceFile(file, write, expected) {
152
+ const suffix = randomBytes(12).toString("hex");
153
+ const temporary = `${file}.${suffix}.tmp`;
154
+ const backup = `${file}.${suffix}.backup`;
155
+ let moved = false;
156
+ const conflict = () => Object.assign(/* @__PURE__ */ new Error(`JSONL file '${file}' changed during the write`), {
157
+ name: "JsonlConflictError",
158
+ file
159
+ });
160
+ try {
161
+ if (write) {
162
+ await write(temporary);
163
+ const mode = await stat(file).catch((error) => {
164
+ if (error.code === "ENOENT") return void 0;
165
+ throw error;
166
+ });
167
+ if (mode) await chmod(temporary, mode.mode & 4095);
168
+ }
169
+ if (expected !== void 0) {
170
+ await rename(file, backup).catch((error) => {
171
+ if (error.code === "ENOENT") throw conflict();
172
+ throw error;
173
+ });
174
+ moved = true;
175
+ if (await readFile(backup, "utf8") !== expected) throw conflict();
176
+ }
177
+ if (write) await link(temporary, file).catch((error) => {
178
+ if (error.code === "EEXIST") throw conflict();
179
+ throw error;
180
+ });
181
+ const cleanBackup = moved;
182
+ moved = false;
183
+ if (cleanBackup) await rm(backup).catch(() => {});
184
+ } catch (error) {
185
+ if (moved) try {
186
+ await link(backup, file);
187
+ moved = false;
188
+ await rm(backup).catch(() => {});
189
+ } catch (restoreError) {
190
+ if (error instanceof Error) {
191
+ error.message += `; original content remains in '${backup}' because it could not be restored`;
192
+ if (write) error.message += `; staged content remains in '${temporary}'`;
193
+ } else throw new Error(`Original content remains in '${backup}' because it could not be restored`, { cause: restoreError });
194
+ }
195
+ throw error;
196
+ } finally {
197
+ if (!moved) await rm(temporary, { force: true }).catch(() => {});
198
+ }
199
+ }
200
+ //#endregion
201
+ export { ok as a, err as i, JsonlReader as n, toError as o, hashJsonlContent as r, unwrap as s, replaceFile as t };
202
+
203
+ //# sourceMappingURL=replace-file-AWLIm7aN.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"replace-file-AWLIm7aN.mjs","names":[],"sources":["../src/result.ts","../src/jsonl-reader.ts","../src/replace-file.ts"],"sourcesContent":["/**\n * A discriminated union for operations that can fail without throwing.\n * Used throughout the JS programmatic API (`LinesDB`, `JsonlReader`) so callers get a typed\n * error back instead of having to wrap every call in try/catch.\n */\nexport type Result<T, E = Error> = { ok: true; value: T } | { ok: false; error: E };\n\nexport function ok<T>(value: T): Result<T, never> {\n return { ok: true, value };\n}\n\nexport function err<E>(error: E): Result<never, E> {\n return { ok: false, error };\n}\n\n/** Normalize a thrown value (which may not be an Error) into an Error. */\nexport function toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value));\n}\n\n/** Unwrap a Result, throwing its error when it is not ok. */\nexport function unwrap<T, E>(result: Result<T, E>): T {\n if (result.ok) return result.value;\n throw result.error;\n}\n","import { createHash } from 'node:crypto';\nimport { readFile } from 'node:fs/promises';\nimport { normalize } from 'node:path';\nimport type { JsonObject, ColumnDefinition, TableSchema, JsonlParseError } from './types.js';\nimport { type Result, ok, err, toError } from './result.js';\n\n/** Fingerprint of a JSONL file's content, to tell whether the file changed since it was read */\nexport function hashJsonlContent(content: string): string {\n return createHash('sha256').update(content).digest('hex');\n}\n\nexport interface JsonlSnapshot {\n /** The rows the content parses into, or why it does not parse */\n rows: Result<JsonObject[], JsonlParseError>;\n /** Undefined when the rows come from an override rather than the file */\n contentHash: string | undefined;\n}\n\nexport class JsonlReader {\n private static overrides: Map<string, JsonObject[]> | null = null;\n\n /**\n * Temporarily override the data returned for specific JSONL files.\n * Useful for scenarios like migration validation where in-memory data should be used.\n */\n static async withOverrides<T>(overrides: Map<string, JsonObject[]>, fn: () => Promise<T>): Promise<T> {\n const normalized = new Map<string, JsonObject[]>();\n for (const [filePath, rows] of overrides) {\n normalized.set(normalize(filePath), rows);\n }\n\n const previousOverrides = this.overrides;\n this.overrides = normalized;\n\n try {\n return await fn();\n } finally {\n this.overrides = previousOverrides;\n }\n }\n\n /**\n * Read JSONL file and parse each line as JSON\n */\n static async read(filePath: string): Promise<Result<JsonObject[], JsonlParseError | Error>> {\n const result = await this.readSnapshot(filePath);\n return result.ok ? result.value.rows : result;\n }\n\n /**\n * Read JSONL file like {@link read}, along with a hash of the content the rows were parsed from.\n * The hash is there even when the content does not parse.\n */\n static async readSnapshot(filePath: string): Promise<Result<JsonlSnapshot, Error>> {\n const overrideRows = this.overrides?.get(normalize(filePath));\n if (overrideRows) {\n // Return clones to avoid accidental mutations from consumers\n return ok({\n rows: ok(overrideRows.map((row) => JSON.parse(JSON.stringify(row)) as JsonObject)),\n contentHash: undefined,\n });\n }\n\n let content: string;\n try {\n content = await readFile(filePath, 'utf-8');\n } catch (error) {\n return err(toError(error));\n }\n\n return ok({ rows: this.parse(filePath, content), contentHash: hashJsonlContent(content) });\n }\n\n private static parse(filePath: string, content: string): Result<JsonObject[], JsonlParseError> {\n const rawLines = (content.startsWith('\\u{feff}') ? content.slice(1) : content).split('\\n');\n\n const rows: JsonObject[] = [];\n for (let i = 0; i < rawLines.length; i++) {\n const line = rawLines[i].endsWith('\\r') ? rawLines[i].slice(0, -1) : rawLines[i];\n if (line.trim().length === 0) continue;\n\n const fail = (message: string, cause?: unknown) => {\n const parseError = new Error(message, { cause }) as JsonlParseError;\n parseError.name = 'JsonlParseError';\n parseError.file = filePath;\n parseError.line = i + 1;\n return err(parseError);\n };\n let value: unknown;\n try {\n value = JSON.parse(line);\n } catch (error) {\n return fail(`Failed to parse JSON line: ${line}`, error);\n }\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return fail(`A JSONL line holds a row, which is a JSON object: ${line}`);\n }\n rows.push(value as JsonObject);\n }\n\n return ok(rows);\n }\n\n /**\n * Infer schema from JSONL data\n */\n static inferSchema(tableName: string, data: JsonObject[]): Result<TableSchema, Error> {\n if (data.length === 0) {\n return err(new Error('Cannot infer schema from empty data'));\n }\n\n const columnTypes = new Map<string, Set<string>>();\n const presence = new Map<string, number>();\n const booleanColumns = new Set<string>();\n const nonBooleanColumns = new Set<string>();\n\n // Collect all column names and their types\n for (const row of data) {\n for (const [key, value] of Object.entries(row)) {\n if (!columnTypes.has(key)) {\n columnTypes.set(key, new Set());\n }\n columnTypes.get(key)!.add(this.inferType(value));\n presence.set(key, (presence.get(key) ?? 0) + 1);\n\n if (typeof value === 'boolean') {\n booleanColumns.add(key);\n } else if (value !== null) {\n nonBooleanColumns.add(key);\n }\n }\n }\n\n // Convert to column definitions\n const columns: ColumnDefinition[] = [];\n for (const [columnName, types] of columnTypes.entries()) {\n const typeArray = Array.from(types);\n\n // If multiple types exist, prefer TEXT as a safe fallback\n let sqlType: ColumnDefinition['type'] = 'TEXT';\n\n if (typeArray.length === 1) {\n sqlType = typeArray[0] as ColumnDefinition['type'];\n } else if (typeArray.every((t) => t === 'INTEGER' || t === 'REAL')) {\n sqlType = 'REAL'; // Use REAL if we have mixed numeric types\n } else if (!typeArray.includes('NULL')) {\n // If there are multiple non-null types, use TEXT\n sqlType = 'TEXT';\n } else if (typeArray.length === 2 && typeArray.includes('NULL')) {\n // If one type + NULL, use the non-null type\n sqlType = typeArray.find((t) => t !== 'NULL') as ColumnDefinition['type'];\n }\n\n const isBooleanColumn = booleanColumns.has(columnName) && !nonBooleanColumns.has(columnName);\n\n columns.push({\n name: columnName,\n type: sqlType,\n // A row without the field stores null for it, so the field is nullable unless every row has it\n notNull: !typeArray.includes('NULL') && presence.get(columnName) === data.length,\n valueType: isBooleanColumn ? 'boolean' : undefined,\n });\n }\n\n // If there's an 'id' column, make it primary key\n const idColumn = columns.find((col) => col.name === 'id');\n if (idColumn) {\n idColumn.primaryKey = true;\n }\n\n return ok({\n name: tableName,\n columns,\n });\n }\n\n private static inferType(value: unknown): string {\n if (value === null || value === undefined) return 'NULL';\n if (typeof value === 'number') {\n return Number.isInteger(value) ? 'INTEGER' : 'REAL';\n }\n if (typeof value === 'string') return 'TEXT';\n if (typeof value === 'boolean') return 'INTEGER'; // SQLite stores booleans as integers\n if (typeof value === 'object') return 'JSON'; // Store objects/arrays as JSON\n return 'TEXT';\n }\n}\n","import { randomBytes } from 'node:crypto';\nimport { chmod, link, readFile, rename, rm, stat } from 'node:fs/promises';\nimport type { JsonlConflictError } from './types.js';\n\nexport async function replaceFile(\n file: string,\n write: ((temporary: string) => Promise<void>) | undefined,\n expected: string | undefined,\n): Promise<void> {\n const suffix = randomBytes(12).toString('hex');\n const temporary = `${file}.${suffix}.tmp`;\n const backup = `${file}.${suffix}.backup`;\n let moved = false;\n const conflict = () =>\n Object.assign(new Error(`JSONL file '${file}' changed during the write`), {\n name: 'JsonlConflictError',\n file,\n }) as JsonlConflictError;\n try {\n if (write) {\n await write(temporary);\n const mode = await stat(file).catch((error: NodeJS.ErrnoException) => {\n if (error.code === 'ENOENT') return undefined;\n throw error;\n });\n if (mode) await chmod(temporary, mode.mode & 0o7777);\n }\n if (expected !== undefined) {\n await rename(file, backup).catch((error: NodeJS.ErrnoException) => {\n if (error.code === 'ENOENT') throw conflict();\n throw error;\n });\n moved = true;\n if ((await readFile(backup, 'utf8')) !== expected) throw conflict();\n }\n if (write) {\n await link(temporary, file).catch((error: NodeJS.ErrnoException) => {\n if (error.code === 'EEXIST') throw conflict();\n throw error;\n });\n }\n const cleanBackup = moved;\n moved = false;\n if (cleanBackup) await rm(backup).catch(() => {});\n } catch (error) {\n if (moved) {\n try {\n await link(backup, file);\n moved = false;\n await rm(backup).catch(() => {});\n } catch (restoreError) {\n if (error instanceof Error) {\n error.message += `; original content remains in '${backup}' because it could not be restored`;\n if (write) error.message += `; staged content remains in '${temporary}'`;\n } else {\n throw new Error(`Original content remains in '${backup}' because it could not be restored`, {\n cause: restoreError,\n });\n }\n }\n }\n throw error;\n } finally {\n if (!moved) await rm(temporary, { force: true }).catch(() => {});\n }\n}\n"],"mappings":";;;;AAOA,SAAgB,GAAM,OAA4B;CAChD,OAAO;EAAE,IAAI;EAAM;CA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B,MAAM,WAAW,kCAAkC,OAAO;IAC1D,IAAI,OAAO,MAAM,WAAW,gCAAgC,UAAU;GACxE,OACE,MAAM,IAAI,MAAM,gCAAgC,OAAO,qCAAqC,EAC1F,OAAO,aACT,CAAC;EAEL;EAEF,MAAM;CACR,UAAU;EACR,IAAI,CAAC,OAAO,MAAM,GAAG,WAAW,EAAE,OAAO,KAAK,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC;CACjE;AACF"}
package/package.json CHANGED
@@ -1,6 +1,75 @@
1
1
  {
2
2
  "name": "lines-db",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.18.0",
4
+ "description": "A database implementation that treats JSONL files as tables using SQLite",
5
+ "type": "module",
6
+ "types": "./dist/index.d.mts",
7
+ "bin": {
8
+ "lines-db": "./bin/cli.mjs"
9
+ },
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.mts",
13
+ "default": "./dist/index.mjs"
14
+ },
15
+ "./internal": {
16
+ "types": "./dist/internal.d.mts",
17
+ "default": "./dist/internal.mjs"
18
+ }
19
+ },
20
+ "files": [
21
+ "dist",
22
+ "bin",
23
+ "CHANGELOG.md"
24
+ ],
25
+ "engines": {
26
+ "node": ">=22.18.0"
27
+ },
28
+ "keywords": [
29
+ "database",
30
+ "jsonl",
31
+ "sqlite",
32
+ "seed-data"
33
+ ],
34
+ "author": "toiroakr",
35
+ "license": "MIT",
36
+ "repository": {
37
+ "type": "git",
38
+ "url": "git+https://github.com/toiroakr/lines-db.git"
39
+ },
40
+ "bugs": {
41
+ "url": "https://github.com/toiroakr/lines-db/issues"
42
+ },
43
+ "homepage": "https://github.com/toiroakr/lines-db#readme",
44
+ "devDependencies": {
45
+ "@loculus/rolldown": "^0.2.3",
46
+ "@types/node": "^24.19.2",
47
+ "publint": "^0.3.25",
48
+ "tsdown": "^0.23.1",
49
+ "type-fest": "^5.10.0",
50
+ "typescript": "^6.0.3",
51
+ "valibot": "^1.5.0",
52
+ "vitest": "^5.0.4"
53
+ },
54
+ "peerDependencies": {
55
+ "typescript": ">=5 <7 || >=7.1.0-0"
56
+ },
57
+ "peerDependenciesMeta": {
58
+ "typescript": {
59
+ "optional": true
60
+ }
61
+ },
62
+ "dependencies": {
63
+ "@politty/loculus": "^0.1.1",
64
+ "@standard-schema/spec": "^1.1.0",
65
+ "amaro": "^1.2.1",
66
+ "loculus": "^0.2.5",
67
+ "zod": "^4.6.6"
68
+ },
69
+ "scripts": {
70
+ "build": "tsdown",
71
+ "publint": "publint",
72
+ "typecheck": "tsc --noEmit",
73
+ "test": "vitest run"
74
+ }
6
75
  }