durable-db 0.3.0 → 0.5.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.
Files changed (34) hide show
  1. package/README.md +177 -25
  2. package/dist/{arktypeConfig-DxP0OcV_.js → actionArgs-1hEaDUia.js} +35 -1
  3. package/dist/cli/bin.js +1 -1
  4. package/dist/cli/index.d.ts +204 -62
  5. package/dist/cli/index.js +4 -3
  6. package/dist/{cli-BUSZTS2D.js → cli-CVS0b2im.js} +272 -95
  7. package/dist/context/index.js +14 -8
  8. package/dist/db/index.d.ts +3 -4
  9. package/dist/db/index.js +259 -26
  10. package/dist/defineDatabase-D_RpcKj1.js +109 -0
  11. package/dist/{defineDatabase-IUthY3Ex.d.ts → defineDatabase-zrUJrMd5.d.ts} +10 -3
  12. package/dist/{index-BdrcuAU7.d.ts → index-BvSFkwM9.d.ts} +106 -18
  13. package/dist/index.d.ts +1 -2
  14. package/dist/index.js +2 -2
  15. package/dist/{kysely-Be6KwFZC.js → kysely-CYmmiwDm.js} +25 -5
  16. package/dist/migrations/generator.d.ts +1 -1
  17. package/dist/migrations/generator.js +1 -1
  18. package/dist/migrations/snapshot.d.ts +2 -2
  19. package/dist/migrations/snapshot.js +1 -91
  20. package/dist/{parser-DR57GOjv.js → parser-DyepmXzE.js} +1 -1
  21. package/dist/registry.d.ts +29 -2
  22. package/dist/registry.js +2 -2
  23. package/dist/snapshot-B9Ae2TrS.d.ts +180 -0
  24. package/dist/snapshot-D_z95s6E.js +459 -0
  25. package/dist/{state-OVuoHRC9.js → state-DGYycIoJ.js} +106 -9
  26. package/dist/testing/index.d.ts +8 -1
  27. package/dist/testing/index.js +30 -11
  28. package/dist/vite/durableDb.d.ts +131 -1
  29. package/dist/vite/durableDb.js +782 -180
  30. package/package.json +3 -2
  31. package/virtual.d.ts +4 -2
  32. package/dist/arktypeConfig-AXvobTPL.d.ts +0 -5
  33. package/dist/defineDatabase-CHmzpzFf.js +0 -70
  34. package/dist/snapshot-CaG5xnE2.d.ts +0 -48
@@ -1,8 +1,8 @@
1
- import { t as type } from "../arktypeConfig-DxP0OcV_.js";
2
- import { t as ACTION_TEST_META } from "../defineDatabase-CHmzpzFf.js";
1
+ import { n as type } from "../actionArgs-1hEaDUia.js";
2
+ import { r as liveTestDatabases, t as ACTION_TEST_META } from "../defineDatabase-D_RpcKj1.js";
3
3
  import { setTenantIdResolver } from "../context/index.js";
4
- import { t as createKyselyFromSql } from "../kysely-Be6KwFZC.js";
5
- import { createEmptySnapshot, generateMigrationStatements, generateSnapshotFromSchema } from "../migrations/snapshot.js";
4
+ import { t as createKyselyFromSql } from "../kysely-CYmmiwDm.js";
5
+ import { i as generateSnapshotFromSchema, n as createEmptySnapshot, r as generateMigrationStatements } from "../snapshot-D_z95s6E.js";
6
6
  import { createRequire } from "node:module";
7
7
  //#region src/testing/index.ts
8
8
  const loadSqlite = () => createRequire(import.meta.url)("node:sqlite");
@@ -48,17 +48,36 @@ async function createTestDatabase(options) {
48
48
  const ddl = statements ?? await deriveStatements(schema);
49
49
  for (const stmt of ddl) sqlite.exec(stmt);
50
50
  setTenantIdResolver(() => tenantId);
51
+ async function run(action, args) {
52
+ const meta = action[ACTION_TEST_META];
53
+ if (!meta) throw new Error("createTestDatabase().run() was given a function that is not a durable-db action (no test metadata). Pass an export created by `action({ … })`.");
54
+ const validated = meta.validator(args);
55
+ if (validated instanceof type.errors) throw new Error(`Invalid args for action: ${validated.summary}`);
56
+ return await meta.handler(db, validated);
57
+ }
58
+ const live = {
59
+ tables: new Set(Object.values(schema)),
60
+ run: (action, args) => run(action, args),
61
+ clear() {
62
+ const tables = sqlite.prepare(`SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite\\_%' ESCAPE '\\'`).all();
63
+ const { foreign_keys: foreignKeys } = sqlite.prepare("PRAGMA foreign_keys").get();
64
+ sqlite.exec("PRAGMA foreign_keys = OFF");
65
+ try {
66
+ for (const { name } of tables) sqlite.exec(`DELETE FROM \`${name.replaceAll("`", "``")}\``);
67
+ } finally {
68
+ sqlite.exec(`PRAGMA foreign_keys = ${foreignKeys ? "ON" : "OFF"}`);
69
+ }
70
+ }
71
+ };
72
+ liveTestDatabases().push(live);
51
73
  return {
52
74
  db,
53
- async run(action, args) {
54
- const meta = action[ACTION_TEST_META];
55
- if (!meta) throw new Error("createTestDatabase().run() was given a function that is not a durable-db action (no test metadata). Pass an export created by `action({ … })`.");
56
- const validated = meta.validator(args);
57
- if (validated instanceof type.errors) throw new Error(`Invalid args for action: ${validated.summary}`);
58
- return await meta.handler(db, validated);
59
- },
75
+ run,
60
76
  sqlite,
61
77
  destroy() {
78
+ const registry = liveTestDatabases();
79
+ const index = registry.indexOf(live);
80
+ if (index !== -1) registry.splice(index, 1);
62
81
  setTenantIdResolver(null);
63
82
  sqlite.close();
64
83
  }
@@ -1,5 +1,130 @@
1
1
  import { t as DatabaseSource } from "../discovery-gHeLq8jk.js";
2
+ import "../index-BvSFkwM9.js";
2
3
  import { Plugin } from "vite";
4
+ //#region src/vite/modules/wrangler.d.ts
5
+ /** A Durable Object binding as wrangler.jsonc declares it. */
6
+ interface DurableObjectBinding {
7
+ name: string;
8
+ class_name: string;
9
+ }
10
+ /** A class rename written as a `renamed_classes` migration. */
11
+ interface ClassRename {
12
+ from: string;
13
+ to: string;
14
+ }
15
+ /**
16
+ * A database's migrations directory moved with its class rename: the renamed
17
+ * Durable Object keeps the old database's tables and `__migrations` journal,
18
+ * so the build must embed the migrations that journal names.
19
+ */
20
+ interface MigrationsMove {
21
+ /** The old database's migrations directory (absolute). */
22
+ from: string;
23
+ /** The renamed database's migrations directory (absolute). */
24
+ to: string;
25
+ }
26
+ /**
27
+ * A stale class and a new database that look like the same database under a
28
+ * new mount, whose rename is not written: moving the data would leave it
29
+ * without the migrations its journal names, or the old migrations directory
30
+ * is not unique. Neither the rename nor a new class is written for the pair
31
+ * until the user resolves it (the warning says how).
32
+ */
33
+ interface RenameConflict extends ClassRename {
34
+ reason: string;
35
+ }
36
+ /**
37
+ * Result of wrangler config patching
38
+ */
39
+ interface PatchResult {
40
+ /** Whether the config was modified */
41
+ modified: boolean;
42
+ /** Path to the config file (if found) */
43
+ configPath: string | null;
44
+ /** Any errors that occurred */
45
+ error: Error | null;
46
+ /** Bindings added for discovered databases. */
47
+ addedBindings: DurableObjectBinding[];
48
+ /**
49
+ * durable-db's own bindings (`<X>_DATABASE_DO` → `<X>DatabaseDO`) removed
50
+ * because their class is no longer a discovered database (the worker
51
+ * exports it only as a tombstone, see {@link tombstoneClasses}).
52
+ */
53
+ removedBindings: DurableObjectBinding[];
54
+ /** Classes added to a `new_sqlite_classes` migration. */
55
+ newClasses: string[];
56
+ /** The tag of the migration written for `newClasses` and `renamedClasses`, if any. */
57
+ migrationTag: string | null;
58
+ /**
59
+ * Classes renamed by a `renamed_classes` migration: a database of a mounted
60
+ * source whose class name changed (its mount changed, or it moved into a
61
+ * mounted source) keeps its deployed data.
62
+ */
63
+ renamedClasses: ClassRename[];
64
+ /** Migrations directories moved with a rename (see {@link MigrationsMove}). */
65
+ movedMigrations: MigrationsMove[];
66
+ /**
67
+ * Renames refused: written neither as a rename nor as a new class until the
68
+ * user resolves them (see {@link RenameConflict}). A production build should
69
+ * fail on them.
70
+ */
71
+ conflicts: RenameConflict[];
72
+ /**
73
+ * Classes of databases that are gone, still declared by the migrations.
74
+ * Deleting a class deletes its data, so the `deleted_classes` migration is
75
+ * never written automatically: the worker exports a tombstone of the class
76
+ * ({@link tombstoneClasses}) and a note gives the exact entry to add.
77
+ */
78
+ deletedClasses: string[];
79
+ }
80
+ //#endregion
81
+ //#region src/vite/modules/syncWrangler.d.ts
82
+ interface SyncWranglerConfigOptions {
83
+ /** Project root (where wrangler.jsonc/json lives). */
84
+ projectRoot: string;
85
+ /** Where database definitions live (default `src/databases`), as for the plugin. */
86
+ databasesDir?: string | DatabaseSource[];
87
+ /**
88
+ * Where production migrations live (default `migrations`), as for the
89
+ * plugin: a mount change moves the database's directory with its class.
90
+ */
91
+ migrationsDir?: string;
92
+ /**
93
+ * Where the one-line summary of a change goes. Default: `console.log`;
94
+ * `false` silences it.
95
+ */
96
+ log?: ((message: string) => void) | false;
97
+ }
98
+ /**
99
+ * What {@link patchWranglerConfig} did (bindings added and removed, classes
100
+ * created and renamed, migrations moved, renames refused, classes left for a
101
+ * hand-written `deleted_classes`), plus the databases and the summary.
102
+ */
103
+ interface SyncWranglerConfigResult extends PatchResult {
104
+ /** The databases discovered. */
105
+ databases: string[];
106
+ /** Database files that did not parse: while there are any, nothing is written. */
107
+ unparsable: string[];
108
+ /** What changed, for the summary line: Durable Object bindings and the migration written. */
109
+ changes: string[];
110
+ }
111
+ /**
112
+ * Discover the databases and reconcile wrangler.jsonc/json with them — before
113
+ * anything reads the config. The Vite plugin runs this in its `config` hook
114
+ * (with `patchWranglerConfig: true`), ahead of @cloudflare/vite-plugin, which
115
+ * reads the worker config in its own `config` hook and emits the build's
116
+ * `wrangler.json` from that copy: patched any later, a build ships the
117
+ * previous bindings, and a dev server restarts while it starts. CLIs that want
118
+ * the file settled before Vite starts can call it themselves; a refused rename
119
+ * is in `conflicts` (the plugin stops on it).
120
+ *
121
+ * When a database file does not parse, nothing is written: the patch is
122
+ * computed from the complete set of databases or not at all (a partial set
123
+ * would read as databases removed). The plugin reports the parse error when
124
+ * it loads the file. A missing config file is reported by the patcher.
125
+ */
126
+ export declare function syncWranglerConfig(options: SyncWranglerConfigOptions): SyncWranglerConfigResult;
127
+ //#endregion
3
128
  //#region src/vite/durableDb.d.ts
4
129
  export interface DurableDbOptions {
5
130
  /** Import path for the context module. Default: 'durable-db/context' */
@@ -15,6 +140,11 @@ export interface DurableDbOptions {
15
140
  * wrangler.jsonc/json automatically. When false (the default), the plugin
16
141
  * only verifies the config and logs the exact JSON to add when something
17
142
  * is missing — your config file is never modified.
143
+ *
144
+ * The write happens in the plugin's `config` hook, before
145
+ * @cloudflare/vite-plugin reads the file, so a build emits a wrangler.json
146
+ * with the new bindings and a dev server does not restart on its first
147
+ * start. A change is logged (`durable-db updated wrangler.jsonc (…)`).
18
148
  */
19
149
  patchWranglerConfig?: boolean;
20
150
  }
@@ -24,4 +154,4 @@ export declare const databasePlugin: typeof durableDb;
24
154
  /** @deprecated Renamed to {@link DurableDbOptions}. */
25
155
  export type DatabasePluginOptions = DurableDbOptions;
26
156
  //#endregion
27
- export { type DatabaseSource, durableDb as default };
157
+ export { type DatabaseSource, type SyncWranglerConfigOptions, type SyncWranglerConfigResult, durableDb as default };