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.
package/dist/index.mjs CHANGED
@@ -1,9 +1,8 @@
1
- import { a as ok, i as err, n as JsonlReader, o as toError, r as hashJsonlContent, s as unwrap, t as replaceFile } from "./replace-file-fStWc0ej.mjs";
1
+ import { a as JsonlReader, c as ok, i as replaceFile, l as toError, n as createSchemaImports, o as hashJsonlContent, r as hashContent, s as err, t as MISSING_HASH, u as unwrap } from "./schema-module-D4j10w8_.mjs";
2
2
  import { createRequire } from "node:module";
3
3
  import { randomBytes } from "node:crypto";
4
4
  import { access, chmod, mkdir, readFile, readdir, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
5
5
  import { basename, dirname, extname, isAbsolute, join, relative, resolve } from "node:path";
6
- import { pathToFileURL } from "node:url";
7
6
  import { styleText } from "node:util";
8
7
  import { z } from "zod";
9
8
  // \0rolldown/runtime.js
@@ -159,13 +158,13 @@ var SchemaLoader = class {
159
158
  * Load a validation schema file for a table
160
159
  * Requires ${tableName}.schema.{ts,mts,cts} to exist in schemaDir, or alongside the JSONL file when omitted
161
160
  */
162
- static async loadSchema(jsonlPath, schemaDir) {
161
+ static async loadSchema(jsonlPath, schemaDir, imports) {
163
162
  const dir = schemaDir ?? dirname(jsonlPath);
164
163
  const tableName = basename(jsonlPath, ".jsonl");
165
164
  const schemaPath = await findSchemaFile(dir, tableName);
166
165
  if (!schemaPath) throw new Error(`Schema file not found for table '${tableName}'. Expected one of: ${SCHEMA_EXTENSIONS.map((ext) => `${tableName}${ext}`).join(", ")}`);
167
166
  try {
168
- const module = await import(`${pathToFileURL(schemaPath).href}?t=${Date.now()}`);
167
+ const module = await (imports ?? createSchemaImports()).import(schemaPath);
169
168
  const schema = module.default || module.schema;
170
169
  if (schema && this.isStandardSchema(schema)) return schema;
171
170
  throw new Error(`Schema file ${schemaPath} does not export a valid StandardSchema`);
@@ -507,6 +506,8 @@ var LinesDB = class LinesDB {
507
506
  tablesFromGivenColumns = /* @__PURE__ */ new Set();
508
507
  /** Each table's schema file and a hash of its content as the tables were loaded, or '' for none */
509
508
  schemaFileStates = /* @__PURE__ */ new Map();
509
+ schemaImports;
510
+ schemaDependencyHashes = /* @__PURE__ */ new Map();
510
511
  constructor(config, dbPath) {
511
512
  this.config = config;
512
513
  this.db = createDatabase(dbPath ?? ":memory:");
@@ -562,13 +563,25 @@ var LinesDB = class LinesDB {
562
563
  const loadingTables = /* @__PURE__ */ new Set();
563
564
  const attemptedTables = /* @__PURE__ */ new Set();
564
565
  const allDeferredForeignKeys = [];
565
- for (const tableNameToLoad of tablesToLoad) if (!attemptedTables.has(tableNameToLoad)) {
566
- const tableTransform = tableNameToLoad === tableName ? transform : void 0;
567
- const { errors, warnings, rowCounts: tableRowCounts, deferredForeignKeys } = await this.loadTableWithDependencies(tableNameToLoad, loadedTables, loadingTables, attemptedTables, detailedValidate, tableTransform);
568
- allErrors.push(...errors);
569
- allWarnings.push(...warnings);
570
- allDeferredForeignKeys.push(...deferredForeignKeys);
571
- for (const [k, v] of tableRowCounts) allRowCounts.set(k, v);
566
+ const imports = createSchemaImports();
567
+ this.schemaImports = imports;
568
+ const schemaPaths = /* @__PURE__ */ new Map();
569
+ for (const [name, config] of this.tables) {
570
+ const schemaPath = await this.findTableSchemaFile(name, config);
571
+ if (schemaPath) schemaPaths.set(name, schemaPath);
572
+ }
573
+ try {
574
+ for (const tableNameToLoad of tablesToLoad) if (!attemptedTables.has(tableNameToLoad)) {
575
+ const tableTransform = tableNameToLoad === tableName ? transform : void 0;
576
+ const { errors, warnings, rowCounts: tableRowCounts, deferredForeignKeys } = await this.loadTableWithDependencies(tableNameToLoad, loadedTables, loadingTables, attemptedTables, detailedValidate, tableTransform);
577
+ allErrors.push(...errors);
578
+ allWarnings.push(...warnings);
579
+ allDeferredForeignKeys.push(...deferredForeignKeys);
580
+ for (const [k, v] of tableRowCounts) allRowCounts.set(k, v);
581
+ }
582
+ } finally {
583
+ this.schemaImports = void 0;
584
+ this.recordSchemaDependencies(imports, attemptedTables, schemaPaths, tableName === void 0);
572
585
  }
573
586
  if (detailedValidate && allDeferredForeignKeys.length > 0) for (const { tableName: tName, foreignKey: fk, filePath } of allDeferredForeignKeys) {
574
587
  if (!loadedTables.has(fk.references.table)) continue;
@@ -593,6 +606,9 @@ var LinesDB = class LinesDB {
593
606
  tableResults
594
607
  };
595
608
  }
609
+ importSchemaModule(schemaPath) {
610
+ return (this.schemaImports ?? createSchemaImports()).import(schemaPath);
611
+ }
596
612
  /**
597
613
  * Load a table and its dependencies recursively
598
614
  */
@@ -615,10 +631,9 @@ var LinesDB = class LinesDB {
615
631
  try {
616
632
  let foreignKeys;
617
633
  try {
618
- const { pathToFileURL } = await import("node:url");
619
634
  const schemaPath = await this.findTableSchemaFile(tableName, tableConfig);
620
635
  if (schemaPath) {
621
- const schemaModule = await import(`${pathToFileURL(schemaPath).href}?t=${Date.now()}`);
636
+ const schemaModule = await this.importSchemaModule(schemaPath);
622
637
  foreignKeys = (schemaModule.schema || schemaModule.default)?.foreignKeys || schemaModule.foreignKeys;
623
638
  }
624
639
  } catch {}
@@ -719,11 +734,10 @@ var LinesDB = class LinesDB {
719
734
  let validationSchema = config.validationSchema;
720
735
  const schemaMetadata = {};
721
736
  const schemaPath = config.validationSchema ? void 0 : await this.findTableSchemaFile(tableName, config);
722
- if (!validationSchema && schemaPath) validationSchema = await SchemaLoader.loadSchema(config.jsonlPath, dirname(schemaPath));
737
+ if (!validationSchema && schemaPath) validationSchema = await SchemaLoader.loadSchema(config.jsonlPath, dirname(schemaPath), this.schemaImports);
723
738
  if (!config.validationSchema) try {
724
- const { pathToFileURL } = await import("node:url");
725
739
  if (!schemaPath) throw new Error("Schema file not found");
726
- const schemaModule = await import(`${pathToFileURL(schemaPath).href}?t=${Date.now()}`);
740
+ const schemaModule = await this.importSchemaModule(schemaPath);
727
741
  const schemaExport = schemaModule.schema || schemaModule.default;
728
742
  if (schemaExport?.primaryKey) schemaMetadata.primaryKey = schemaExport.primaryKey;
729
743
  else if (schemaModule.primaryKey) schemaMetadata.primaryKey = schemaModule.primaryKey;
@@ -2263,7 +2277,8 @@ var LinesDB = class LinesDB {
2263
2277
  }
2264
2278
  /**
2265
2279
  * The files that changed since this database last read or wrote them, as {@link hasExternalChanges}
2266
- * tells: each JSONL file edited, added or removed, and each schema file edited, added or removed
2280
+ * tells: each JSONL file edited, added or removed, each schema file edited, added or removed, and each
2281
+ * project file a schema imports edited, added or removed
2267
2282
  */
2268
2283
  async findExternalChanges() {
2269
2284
  try {
@@ -2282,6 +2297,16 @@ var LinesDB = class LinesDB {
2282
2297
  });
2283
2298
  if (content === void 0 || hashJsonlContent(content) !== knownHash) changed.add(file);
2284
2299
  }
2300
+ const knownHashes = /* @__PURE__ */ new Map();
2301
+ for (const files of this.schemaDependencyHashes.values()) for (const [file, knownHash] of files) knownHashes.set(file, (knownHashes.get(file) ?? /* @__PURE__ */ new Set()).add(knownHash));
2302
+ for (const [file, hashes] of knownHashes) {
2303
+ const content = await readFile(file).catch((error) => {
2304
+ if (error.code === "ENOENT") return void 0;
2305
+ throw error;
2306
+ });
2307
+ const current = content === void 0 ? MISSING_HASH : hashContent(content);
2308
+ if ([...hashes].some((hash) => hash !== current)) changed.add(file);
2309
+ }
2285
2310
  const tables = await DirectoryScanner.scanDirectory(this.config.dataDir);
2286
2311
  const scanned = new Set(listJsonlFiles(tables));
2287
2312
  for (const file of this.scannedJsonlFiles) if (!scanned.has(file)) changed.add(file);
@@ -2304,6 +2329,25 @@ var LinesDB = class LinesDB {
2304
2329
  });
2305
2330
  return content === void 0 ? "" : `${schemaPath}\0${hashJsonlContent(content)}`;
2306
2331
  }
2332
+ recordSchemaDependencies(imports, tableNames, schemaPaths, replace) {
2333
+ if (replace) {
2334
+ for (const name of this.schemaDependencyHashes.keys()) if (!schemaPaths.has(name)) this.schemaDependencyHashes.delete(name);
2335
+ }
2336
+ for (const name of tableNames) {
2337
+ const schemaPath = schemaPaths.get(name);
2338
+ if (schemaPath) this.schemaDependencyHashes.set(name, imports.dependencies(schemaPath));
2339
+ else this.schemaDependencyHashes.delete(name);
2340
+ }
2341
+ }
2342
+ /**
2343
+ * The project files the schemas import, as paths: not the schema files, and not a package from
2344
+ * node_modules. Those of one table when it is given. An edit to one of them is among
2345
+ * {@link findExternalChanges}
2346
+ */
2347
+ listSchemaDependencies(tableName) {
2348
+ const tables = tableName === void 0 ? [...this.schemaDependencyHashes.values()] : [this.schemaDependencyHashes.get(tableName) ?? /* @__PURE__ */ new Map()];
2349
+ return [...new Set(tables.flatMap((files) => [...files.keys()]))];
2350
+ }
2307
2351
  async schemaFileState(tableName, config) {
2308
2352
  if (config.validationSchema) return "";
2309
2353
  const schemaPath = await this.findTableSchemaFile(tableName, config);
@@ -2520,13 +2564,14 @@ async function fillFieldsInternal(options) {
2520
2564
  const loadFiller = options.loadFiller ?? fillerFromValidationSchema;
2521
2565
  const tablesWithoutSchema = [];
2522
2566
  const tables = [];
2567
+ const imports = createSchemaImports();
2523
2568
  for (const { table, file, target, schemaDir } of sources.values()) {
2524
2569
  const schemaPath = await findSchemaFile(schemaDir, table);
2525
2570
  if (!schemaPath) {
2526
2571
  if (!tablesWithoutSchema.includes(table)) tablesWithoutSchema.push(table);
2527
2572
  continue;
2528
2573
  }
2529
- const schemaModule = await import(`${pathToFileURL(schemaPath).href}?t=${Date.now()}`);
2574
+ const schemaModule = await imports.import(schemaPath);
2530
2575
  tables.push({
2531
2576
  table,
2532
2577
  file,