@lines-db/studio 0.16.4 → 0.16.6

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/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # @lines-db/studio
2
2
 
3
+ ## 0.16.6
4
+
5
+ ### Patch Changes
6
+
7
+ - 4bfd4b7: Read the files a schema file imports anew when one of them changed, so an edit to a project file the schema imports, such as a table definition, is validated against instead of the version first loaded. Once the first read has recorded the imports, a file is evaluated again only when it or a file it imports changed, except after a read that failed, so reading the tables again many times does not grow memory with the number of files. A package from `node_modules`, and a file of another package, such as one linked from a workspace, stay one module. A runtime without synchronous module hooks still reads only the schema file itself again, and CommonJS schemas (`.schema.cts`) keep their first evaluation, as before.
8
+
9
+ `hasExternalChanges()` and `findExternalChanges()` now report an edit to, or the removal of, a project file the schemas imported, so the studio reloads when only a table definition changed. `listSchemaDependencies()` lists the project files a database's schemas imported. With synchronous module hooks, a relative import of a file that was not there when the tables were read is tracked too, so creating the file is reported as a change. Calling `initialize()` again in the same process before an earlier call has finished can leave `hasExternalChanges()` reporting no change for a file edited while the earlier call was reading; the studio reads the tables one reload at a time and is not affected. The studio watches the imported files too, so an open page is told as soon as one of them is edited or created, even when it is outside the watched directories; a file that is not there yet is watched through the directory that would hold it, or the nearest one that exists.
10
+ - Updated dependencies [4bfd4b7]
11
+ - lines-db@0.19.1
12
+
13
+ ## 0.16.5
14
+
15
+ ### Patch Changes
16
+
17
+ - 3833022: Watch the data and schema directories with `zygiella` instead of `fs.watch` for live reload. The Node.js requirement of Studio is now 22.18.0 or later, the same as `lines-db`, which Studio already depends on as a peer.
18
+
3
19
  ## 0.16.4
4
20
 
5
21
  ### Patch Changes
package/README.ja.md CHANGED
@@ -6,7 +6,7 @@ Studioは[lines-db](https://github.com/toiroakr/lines-db)のブラウザ用エ
6
6
 
7
7
  ## 起動する
8
8
 
9
- Node.js 22.12.0以降が必要です。プロジェクトに両方のパッケージをインストールします。
9
+ Node.js 22.18.0以降が必要です。プロジェクトに両方のパッケージをインストールします。
10
10
 
11
11
  ```bash
12
12
  npm install -D lines-db @lines-db/studio
@@ -69,7 +69,7 @@ npx lines-db studio --data-dir seed/data --data-dir seed/data/cogs --schema-dir
69
69
 
70
70
  ## 他のツールでファイルを変更した場合
71
71
 
72
- Studioはディスク上のファイルを監視します。未保存の編集がなければ変更後のデータを読み直し、編集が残っていれば通知を表示します。
72
+ Studioはディスク上のファイルを監視します。スキーマがimportするテーブル定義などのプロジェクト内ファイルも対象です。未保存の編集がなければ変更後のデータを読み直し、編集が残っていれば通知を表示します。
73
73
 
74
74
  保存前にスキーマの変更を確認し、変更されていれば読み直して検証します。書き込み対象のファイルが変更されていた場合は、何も書き込まずに保存を中止します。ファイル名を表示し、テーブルを読み直します。`CASCADE`や`SET NULL`などの外部キーの操作で変更されるテーブルも対象です。無関係なテーブルのファイルの変更では保存を中止しません。
75
75
 
package/README.md CHANGED
@@ -6,7 +6,7 @@ Studio is a browser editor for [lines-db](https://github.com/toiroakr/lines-db).
6
6
 
7
7
  ## Start Studio
8
8
 
9
- Requires Node.js 22.12.0 or later. Install both packages in the project.
9
+ Requires Node.js 22.18.0 or later. Install both packages in the project.
10
10
 
11
11
  ```bash
12
12
  npm install -D lines-db @lines-db/studio
@@ -69,7 +69,7 @@ Updates and deletions go back to each row's source file. In **Add record**, choo
69
69
 
70
70
  ## Changes made outside Studio
71
71
 
72
- Studio watches the files on disk. With no pending edits, it reloads changed data automatically. With pending edits, it shows a notice.
72
+ Studio watches the files on disk, including the project files the schemas import, such as a table definition. With no pending edits, it reloads changed data automatically. With pending edits, it shows a notice.
73
73
 
74
74
  Before saving, Studio reloads changed schemas and validates against them. If a file that the save would write has changed, the save stops, names the file, and reloads the tables without writing. This includes tables affected by foreign key actions such as `CASCADE` or `SET NULL`. Changes to unrelated table files do not stop the save.
75
75
 
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/server.ts"],"mappings":";UA8BiB;EACf;EACA;;EAEA;;EAEA,oBAAoB;EACpB;EACA;;UAGe;EACf;;EAEA;EACA,SAAS;;wBAwBW,kBAAkB,SAAS,sBAAsB,QAAQ"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/server.ts"],"mappings":";UA+BiB;EACf;EACA;;EAEA;;EAEA,oBAAoB;EACpB;EACA;;UAGe;EACf;;EAEA;EACA,SAAS;;wBAwBW,kBAAkB,SAAS,sBAAsB,QAAQ"}
package/dist/index.mjs CHANGED
@@ -1,12 +1,13 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { randomBytes, timingSafeEqual } from "node:crypto";
3
- import { watch } from "node:fs";
3
+ import { existsSync } from "node:fs";
4
4
  import { readFile, realpath, stat, writeFile } from "node:fs/promises";
5
5
  import { createServer } from "node:http";
6
6
  import { basename, dirname, extname, join, relative, resolve, win32 } from "node:path";
7
7
  import { fileURLToPath, pathToFileURL } from "node:url";
8
+ import { watch } from "zygiella";
8
9
  import { DirectoryScanner, ErrorFormatter, JsonlReader, LinesDB, findSchemaFile, unwrap } from "lines-db";
9
- import { hashJsonlContent, replaceFile } from "lines-db/internal";
10
+ import { createSchemaImports, hashJsonlContent, replaceFile } from "lines-db/internal";
10
11
  // src/declared-columns.ts
11
12
  const CORSA_NULL = 8;
12
13
  const CORSA_UNION = 134217728;
@@ -277,7 +278,14 @@ async function startStudioServer(options) {
277
278
  const uiDir = options.uiDir ?? shippedUiDir();
278
279
  const token = randomBytes(24).toString("base64url");
279
280
  const writeFilledValues = options.writeFilledValues ?? "primaryKey";
280
- const load = () => loadSnapshot(dataDirs, options.schemaDir, writeFilledValues);
281
+ let failedDependencies = [];
282
+ const load = async () => {
283
+ const loaded = await loadSnapshot(dataDirs, options.schemaDir, writeFilledValues, (files) => {
284
+ failedDependencies = files;
285
+ });
286
+ failedDependencies = [];
287
+ return loaded;
288
+ };
281
289
  let snapshot = await load();
282
290
  let queue = Promise.resolve();
283
291
  const serialize = (fn) => {
@@ -288,7 +296,11 @@ async function startStudioServer(options) {
288
296
  /** Reload the tables when a JSONL file no longer holds what they were read from; true if it did */
289
297
  const reloadUnlocked = async () => {
290
298
  const previous = snapshot;
291
- snapshot = await load();
299
+ try {
300
+ snapshot = await load();
301
+ } finally {
302
+ watchDependencies();
303
+ }
292
304
  await previous.db.close();
293
305
  };
294
306
  const reloadIfChangedUnlocked = async () => {
@@ -347,26 +359,71 @@ async function startStudioServer(options) {
347
359
  const notifyChanged = () => {
348
360
  for (const client of eventClients) client.write("event: changed\ndata: {}\n\n");
349
361
  };
362
+ const reloadIfChanged = () => serialize(reloadIfChangedUnlocked);
350
363
  let watchTimer;
351
- const watchers = [.../* @__PURE__ */ new Set([...dataDirs, resolve(schemaDir)])].flatMap((dir) => {
364
+ const scheduleReload = () => {
365
+ clearTimeout(watchTimer);
366
+ watchTimer = setTimeout(() => {
367
+ reloadIfChanged().catch(notifyChanged);
368
+ }, 100);
369
+ };
370
+ const watchers = (await Promise.all([.../* @__PURE__ */ new Set([...dataDirs, resolve(schemaDir)])].map(async (dir) => {
352
371
  try {
353
- const watcher = watch(dir, () => {
354
- clearTimeout(watchTimer);
355
- watchTimer = setTimeout(() => {
356
- reloadIfChanged().catch(notifyChanged);
357
- }, 100);
372
+ const watcher = watch(dir, {
373
+ ignoreInitial: true,
374
+ depth: 0
358
375
  });
376
+ watcher.on("all", scheduleReload);
359
377
  watcher.on("error", (error) => {
360
378
  console.warn(`Live reload is off for '${dir}': ${errorMessage(error)}`);
361
379
  watcher.close();
362
380
  });
381
+ const { missing } = await watcher.ready;
382
+ if (missing.length > 0) {
383
+ console.warn(`Live reload is off for '${dir}': the directory does not exist`);
384
+ await watcher.close();
385
+ return [];
386
+ }
363
387
  return [watcher];
364
388
  } catch (error) {
365
389
  console.warn(`Live reload is off for '${dir}': ${errorMessage(error)}`);
366
390
  return [];
367
391
  }
368
- });
369
- const reloadIfChanged = () => serialize(reloadIfChangedUnlocked);
392
+ }))).flat();
393
+ const existingPathOf = (file) => {
394
+ let path = file;
395
+ while (!existsSync(path) && dirname(path) !== path) path = dirname(path);
396
+ return path;
397
+ };
398
+ let dependencyWatcher;
399
+ let watchedDependencies = [];
400
+ const watchDependencies = () => {
401
+ const wanted = [...new Set([...snapshot.db.listSchemaDependencies(), ...failedDependencies].map(existingPathOf))];
402
+ if (!dependencyWatcher) {
403
+ if (wanted.length === 0) return;
404
+ try {
405
+ const created = watch(wanted, {
406
+ ignoreInitial: true,
407
+ depth: 0
408
+ });
409
+ created.on("all", scheduleReload);
410
+ created.on("error", (error) => {
411
+ console.warn(`Live reload is off for the files the schemas import: ${errorMessage(error)}`);
412
+ created.close();
413
+ if (dependencyWatcher === created) dependencyWatcher = void 0;
414
+ });
415
+ dependencyWatcher = created;
416
+ } catch (error) {
417
+ console.warn(`Live reload is off for the files the schemas import: ${errorMessage(error)}`);
418
+ return;
419
+ }
420
+ } else {
421
+ dependencyWatcher.unwatch(watchedDependencies.filter((file) => !wanted.includes(file)));
422
+ dependencyWatcher.add(wanted.filter((file) => !watchedDependencies.includes(file)));
423
+ }
424
+ watchedDependencies = wanted;
425
+ };
426
+ watchDependencies();
370
427
  const server = createServer((req, res) => {
371
428
  handle(req, res).catch((error) => sendJson(res, error instanceof BadRequestError ? 400 : 500, { message: errorMessage(error) }));
372
429
  });
@@ -687,10 +744,11 @@ async function startStudioServer(options) {
687
744
  const outcome = await serialize(async () => {
688
745
  const changedFiles = unwrap(await snapshot.db.findExternalChanges());
689
746
  if (changedFiles.length > 0) {
747
+ const tableImports = snapshot.db.listSchemaDependencies(tableName);
690
748
  await reloadUnlocked();
691
749
  reloaded = true;
692
750
  if (write.kind === "check") changedFiles.length = 0;
693
- const ownFile = changedFiles.find((file) => dataDirs.some((dir) => resolve(file) === resolve(dir, `${tableName}.jsonl`)) || basename(file).startsWith(`${tableName}.schema.`));
751
+ const ownFile = changedFiles.find((file) => dataDirs.some((dir) => resolve(file) === resolve(dir, `${tableName}.jsonl`)) || basename(file).startsWith(`${tableName}.schema.`) || tableImports.includes(file));
694
752
  if (ownFile) return {
695
753
  status: 409,
696
754
  body: { message: `${relative(dataDir, ownFile) || ownFile} changed on disk, so the tables were reloaded. Check the rows and try again.` },
@@ -786,7 +844,7 @@ async function startStudioServer(options) {
786
844
  });
787
845
  });
788
846
  } catch (error) {
789
- watchers.forEach((watcher) => watcher.close());
847
+ await Promise.all([...watchers, dependencyWatcher].map((watcher) => watcher?.close()));
790
848
  await snapshot.db.close();
791
849
  throw error;
792
850
  }
@@ -795,7 +853,7 @@ async function startStudioServer(options) {
795
853
  url: `http://${host.includes(":") ? `[${host}]` : host}:${port}`,
796
854
  token,
797
855
  close: async () => {
798
- watchers.forEach((watcher) => watcher.close());
856
+ await Promise.all([...watchers, dependencyWatcher].map((watcher) => watcher?.close()));
799
857
  clearTimeout(watchTimer);
800
858
  server.closeAllConnections();
801
859
  await new Promise((resolve) => server.close(() => resolve()));
@@ -806,7 +864,7 @@ async function startStudioServer(options) {
806
864
  async function replaceUnchangedFile(file, next, expected) {
807
865
  await replaceFile(file, (temporary) => writeFile(temporary, next, "utf8"), expected);
808
866
  }
809
- async function loadSnapshot(dataDir, schemaDir, writeFilledValues) {
867
+ async function loadSnapshot(dataDir, schemaDir, writeFilledValues, onFailure) {
810
868
  const db = LinesDB.create({
811
869
  dataDir,
812
870
  schemaDir,
@@ -820,6 +878,7 @@ async function loadSnapshot(dataDir, schemaDir, writeFilledValues) {
820
878
  const baseDir = [dataDir].flat()[0];
821
879
  const loaded = await db.initialize({ detailedValidate: true });
822
880
  if (!loaded.ok) {
881
+ onFailure(db.listSchemaDependencies());
823
882
  await db.close();
824
883
  if (loaded.error.name === "JsonlParseError") {
825
884
  const { file, line, message } = loaded.error;
@@ -897,7 +956,7 @@ async function foreignKeysInFile(dataDir, tableName) {
897
956
  const schemaPath = await findSchemaFile(dataDir, tableName);
898
957
  if (!schemaPath) return [];
899
958
  try {
900
- const module = await import(`${pathToFileURL(schemaPath).href}?t=${Date.now()}`);
959
+ const module = await createSchemaImports().import(schemaPath);
901
960
  return (module.schema ?? module.default)?.foreignKeys ?? module.foreignKeys ?? [];
902
961
  } catch {
903
962
  return [];