durable-db 0.1.13 → 0.2.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.
Files changed (52) hide show
  1. package/dist/arktypeConfig-DdIO8VV1.d.ts +6130 -0
  2. package/dist/{arktypeConfig-CTCJm4vA.js → arktypeConfig-DxP0OcV_.js} +1014 -1033
  3. package/dist/cli/bin.d.ts +1 -1
  4. package/dist/cli/bin.js +2 -10
  5. package/dist/cli/index.d.ts +40 -34
  6. package/dist/cli/index.js +4 -9
  7. package/dist/{cli-m2H7mQpa.js → cli-BUSZTS2D.js} +213 -49
  8. package/dist/context/index.d.ts +50 -2
  9. package/dist/context/index.js +119 -5
  10. package/dist/db/index.d.ts +4 -4
  11. package/dist/db/index.js +10 -12
  12. package/dist/{debug-DmBrUmwe.js → debug-Cz8KzMft.js} +23 -27
  13. package/dist/{defineDatabase-Bjws1Jkd.d.ts → defineDatabase-CHmTgZTx.d.ts} +4 -5
  14. package/dist/{defineDatabase-BD3k1L7d.js → defineDatabase-CHmzpzFf.js} +2 -4
  15. package/dist/discovery-gHeLq8jk.d.ts +11 -0
  16. package/dist/{index-AbdSa1Mk.d.ts → index-M4Jp_PFM.d.ts} +2 -1
  17. package/dist/index.d.ts +4 -4
  18. package/dist/index.js +5 -8
  19. package/dist/{kysely-BH7QZBZw.js → kysely-Be6KwFZC.js} +45 -31
  20. package/dist/migrations/generator.d.ts +14 -17
  21. package/dist/migrations/generator.js +202 -5
  22. package/dist/migrations/snapshot.d.ts +1 -1
  23. package/dist/migrations/snapshot.js +91 -3
  24. package/dist/{parser-CL3Nlmsy.js → parser-DR57GOjv.js} +58 -61
  25. package/dist/registry.d.ts +10 -11
  26. package/dist/registry.js +3 -5
  27. package/dist/schema.d.ts +5 -2
  28. package/dist/schema.js +6 -3
  29. package/dist/snapshot-CaG5xnE2.d.ts +48 -0
  30. package/dist/{state-DtZ70cBR.js → state-OVuoHRC9.js} +3 -5
  31. package/dist/testing/index.d.ts +4 -5
  32. package/dist/testing/index.js +6 -10
  33. package/dist/transport/protocol.d.ts +7 -8
  34. package/dist/transport/protocol.js +34 -3
  35. package/dist/transport/websocket.d.ts +4 -5
  36. package/dist/transport/websocket.js +103 -3
  37. package/dist/vite/durableDb.d.ts +7 -7
  38. package/dist/vite/durableDb.js +29 -31
  39. package/package.json +12 -12
  40. package/dist/arktypeConfig--4OgOv4U.d.ts +0 -6
  41. package/dist/context-kIVZbhye.js +0 -121
  42. package/dist/generator-KHBZaOI1.js +0 -202
  43. package/dist/index-BhRiKZ4j.d.ts +0 -51
  44. package/dist/protocol-DEubbBbR.js +0 -35
  45. package/dist/push-BY3lfh-R.js +0 -8
  46. package/dist/push-DiHH52-G.js +0 -190
  47. package/dist/schema-BCjqTRvV.d.ts +0 -6
  48. package/dist/schema-IFq7ovQq.js +0 -8
  49. package/dist/snapshot-DMW6j2Ix.js +0 -93
  50. package/dist/snapshot-DOerumb7.d.ts +0 -125
  51. package/dist/state-vav3VCId.js +0 -5
  52. package/dist/websocket-eao2rnHL.js +0 -104
package/dist/cli/bin.d.ts CHANGED
@@ -1 +1 @@
1
- export { };
1
+ export {}
package/dist/cli/bin.js CHANGED
@@ -1,18 +1,10 @@
1
1
  #!/usr/bin/env node
2
- import "../debug-DmBrUmwe.js";
3
- import "../state-DtZ70cBR.js";
4
- import "../snapshot-DMW6j2Ix.js";
5
- import "../generator-KHBZaOI1.js";
6
- import "../parser-CL3Nlmsy.js";
7
- import "../push-DiHH52-G.js";
8
- import { n as registerDbCommands } from "../cli-m2H7mQpa.js";
2
+ import { n as registerDbCommands } from "../cli-BUSZTS2D.js";
9
3
  import { Command } from "commander";
10
-
11
4
  //#region src/cli/bin.ts
12
5
  const program = new Command();
13
6
  program.name("db").description("Database migration management").version("0.0.1");
14
7
  registerDbCommands(program);
15
8
  program.parse();
16
-
17
9
  //#endregion
18
- export { };
10
+ export {};
@@ -1,10 +1,9 @@
1
- import { t as Snapshot } from "../snapshot-DOerumb7.js";
2
- import { l as DatabaseInfo } from "../defineDatabase-Bjws1Jkd.js";
3
- import "../index-AbdSa1Mk.js";
1
+ import { t as DatabaseSource } from "../discovery-gHeLq8jk.js";
2
+ import { t as Snapshot } from "../snapshot-CaG5xnE2.js";
3
+ import { l as DatabaseInfo } from "../defineDatabase-CHmTgZTx.js";
4
+ import "../index-M4Jp_PFM.js";
4
5
  import { Command } from "commander";
5
-
6
6
  //#region src/cli/command.d.ts
7
-
8
7
  /**
9
8
  * Register all database subcommands (push, generate, status, reset,
10
9
  * validate) directly on the given Commander command.
@@ -18,14 +17,20 @@ import { Command } from "commander";
18
17
  *
19
18
  * program.addCommand(createDbCommand()); // → `mycli db push`
20
19
  */
21
- declare function registerDbCommands(program: Command): Command;
20
+ interface DbCommandDefaults {
21
+ /** Where databases are discovered when `-d` is not given (default `src/databases`). */
22
+ databasesDir?: string | DatabaseSource[];
23
+ /** Where production migrations live when `-m` is not given (default `migrations`). */
24
+ migrationsDir?: string;
25
+ }
26
+ export declare function registerDbCommands(program: Command, defaults?: DbCommandDefaults): Command;
22
27
  /**
23
28
  * Create a Commander command group named `db` with all database
24
29
  * subcommands. Mount it in a host CLI with
25
30
  * `program.addCommand(createDbCommand())` so the commands live under a
26
31
  * `db` prefix (e.g. `mycli db push`).
27
32
  */
28
- declare function createDbCommand(): Command;
33
+ export declare function createDbCommand(defaults?: DbCommandDefaults): Command;
29
34
  //#endregion
30
35
  //#region src/cli/state.d.ts
31
36
  interface DatabaseDevState {
@@ -55,37 +60,37 @@ interface DevPaths {
55
60
  /**
56
61
  * Get all dev-related paths for a project
57
62
  */
58
- declare function getDevPaths(projectRoot: string): DevPaths;
63
+ export declare function getDevPaths(projectRoot: string): DevPaths;
59
64
  /**
60
65
  * Generate a new epoch value (timestamp-based)
61
66
  */
62
- declare function generateEpoch(): string;
67
+ export declare function generateEpoch(): string;
63
68
  /**
64
69
  * Load the dev state from disk
65
70
  */
66
- declare function loadDevState(projectRoot: string): DevState;
71
+ export declare function loadDevState(projectRoot: string): DevState;
67
72
  /**
68
73
  * Save the dev state to disk
69
74
  */
70
- declare function saveDevState(projectRoot: string, state: DevState): void;
75
+ export declare function saveDevState(projectRoot: string, state: DevState): void;
71
76
  /**
72
77
  * Load dev migrations for a database
73
78
  */
74
- declare function loadDevMigrations(projectRoot: string, dbName: string): Map<string, string[][]>;
79
+ export declare function loadDevMigrations(projectRoot: string, dbName: string): Map<string, string[][]>;
75
80
  /**
76
81
  * Get the dev epoch for instance key suffixing
77
82
  * Returns null in production or if no dev state exists
78
83
  */
79
- declare function getDevEpoch(projectRoot: string): string | null;
84
+ export declare function getDevEpoch(projectRoot: string): string | null;
80
85
  /**
81
86
  * Get a database instance key with optional dev epoch suffix
82
87
  */
83
- declare function getInstanceKey(baseKey: string, epoch: string | null): string;
88
+ export declare function getInstanceKey(baseKey: string, epoch: string | null): string;
84
89
  //#endregion
85
90
  //#region src/cli/push.d.ts
86
91
  interface PushContext {
87
92
  projectRoot?: string;
88
- databasesDir?: string;
93
+ databasesDir?: string | DatabaseSource[];
89
94
  migrationsDir?: string;
90
95
  verbose?: boolean;
91
96
  }
@@ -108,17 +113,17 @@ interface PushResult {
108
113
  * Dev migrations are stored in node_modules/.cache/durable-db/
109
114
  * and are ephemeral - they're cleared when running `db:generate` or `db:reset`
110
115
  */
111
- declare function push(ctx?: PushContext): Promise<PushResult[]>;
116
+ export declare function push(ctx?: PushContext): Promise<PushResult[]>;
112
117
  /**
113
118
  * Push a single database by name
114
119
  * Useful when you only want to push one specific database
115
120
  */
116
- declare function pushOne(ctx: PushContext | undefined, dbName: string): Promise<PushResult | null>;
121
+ export declare function pushOne(ctx: PushContext | undefined, dbName: string): Promise<PushResult | null>;
117
122
  //#endregion
118
123
  //#region src/cli/generate.d.ts
119
124
  interface GenerateContext {
120
125
  projectRoot?: string;
121
- databasesDir?: string;
126
+ databasesDir?: string | DatabaseSource[];
122
127
  migrationsDir?: string;
123
128
  verbose?: boolean;
124
129
  }
@@ -147,16 +152,16 @@ interface GenerateResult {
147
152
  * Unlike `push`, this writes to the actual migrations directory
148
153
  * that gets committed to git.
149
154
  */
150
- declare function generate(ctx?: GenerateContext, options?: GenerateOptions): Promise<GenerateResult[]>;
155
+ export declare function generate(ctx?: GenerateContext, options?: GenerateOptions): Promise<GenerateResult[]>;
151
156
  /**
152
157
  * Generate migration for a single database by name
153
158
  */
154
- declare function generateOne(ctx: GenerateContext, dbName: string, options?: Omit<GenerateOptions, 'database'>): Promise<GenerateResult | null>;
159
+ export declare function generateOne(ctx: GenerateContext, dbName: string, options?: Omit<GenerateOptions, 'database'>): Promise<GenerateResult | null>;
155
160
  //#endregion
156
161
  //#region src/cli/reset.d.ts
157
162
  interface ResetContext {
158
163
  projectRoot?: string;
159
- databasesDir?: string;
164
+ databasesDir?: string | DatabaseSource[];
160
165
  migrationsDir?: string;
161
166
  verbose?: boolean;
162
167
  }
@@ -198,12 +203,12 @@ interface ResetResult {
198
203
  * - Your local DB is in a broken state
199
204
  * - Someone else committed migrations and you pulled
200
205
  */
201
- declare function reset(ctx?: ResetContext, options?: ResetOptions): Promise<ResetResult>;
206
+ export declare function reset(ctx?: ResetContext, options?: ResetOptions): Promise<ResetResult>;
202
207
  /**
203
208
  * Reset everything and re-run push
204
209
  * Convenience function that combines reset + push
205
210
  */
206
- declare function resetAndPush(ctx?: ResetContext, options?: ResetOptions): Promise<{
211
+ export declare function resetAndPush(ctx?: ResetContext, options?: ResetOptions): Promise<{
207
212
  reset: ResetResult;
208
213
  push: PushResult[];
209
214
  }>;
@@ -211,7 +216,7 @@ declare function resetAndPush(ctx?: ResetContext, options?: ResetOptions): Promi
211
216
  //#region src/cli/status.d.ts
212
217
  interface StatusContext {
213
218
  projectRoot?: string;
214
- databasesDir?: string;
219
+ databasesDir?: string | DatabaseSource[];
215
220
  migrationsDir?: string;
216
221
  verbose?: boolean;
217
222
  }
@@ -247,16 +252,16 @@ interface StatusResult {
247
252
  * - Whether there are uncommitted schema changes
248
253
  * - What SQL would be generated
249
254
  */
250
- declare function status(ctx?: StatusContext): Promise<StatusResult>;
255
+ export declare function status(ctx?: StatusContext): Promise<StatusResult>;
251
256
  /**
252
257
  * Format status for display
253
258
  */
254
- declare function formatStatus(result: StatusResult): string;
259
+ export declare function formatStatus(result: StatusResult): string;
255
260
  //#endregion
256
261
  //#region src/cli/validate.d.ts
257
262
  interface ValidateContext {
258
263
  projectRoot?: string;
259
- databasesDir?: string;
264
+ databasesDir?: string | DatabaseSource[];
260
265
  migrationsDir?: string;
261
266
  verbose?: boolean;
262
267
  /** Skip dev migrations, only validate prod */
@@ -284,7 +289,7 @@ interface ValidateResult {
284
289
  * before deployment. Optionally compares the migrated schema against a
285
290
  * from-scratch schema build (dual-path verification).
286
291
  */
287
- declare function validate(ctx?: ValidateContext): Promise<ValidateResult[]>;
292
+ export declare function validate(ctx?: ValidateContext): Promise<ValidateResult[]>;
288
293
  //#endregion
289
294
  //#region src/cli/shared.d.ts
290
295
  /**
@@ -292,10 +297,11 @@ declare function validate(ctx?: ValidateContext): Promise<ValidateResult[]>;
292
297
  * (flag or `DEBUG=*`) is set, also prints the stack so users can diagnose
293
298
  * unexpected failures without patching the CLI.
294
299
  */
295
- declare function reportCliError(error: unknown, verbose?: boolean): void;
300
+ export declare function reportCliError(error: unknown, verbose?: boolean): void;
296
301
  interface DiscoverOptions {
297
302
  projectRoot: string;
298
- databasesDir: string;
303
+ /** A directory, or several with name prefixes — see DiscoveryOptions. */
304
+ databasesDir: string | DatabaseSource[];
299
305
  migrationsDir: string;
300
306
  /** Only return databases matching this name */
301
307
  database?: string;
@@ -310,7 +316,7 @@ interface DiffResult {
310
316
  * Discover database files, parse them, and resolve migrationsDir.
311
317
  * Returns parsed DatabaseInfo[] with migrationsDir already set.
312
318
  */
313
- declare function discoverDatabases(opts: DiscoverOptions): DatabaseInfo[];
319
+ export declare function discoverDatabases(opts: DiscoverOptions): DatabaseInfo[];
314
320
  /**
315
321
  * Load and validate schema for a database.
316
322
  *
@@ -325,11 +331,11 @@ declare function discoverDatabases(opts: DiscoverOptions): DatabaseInfo[];
325
331
  * (cached) and used as the source of truth. Omit it to resolve relative
326
332
  * imports only.
327
333
  */
328
- declare function loadSchema(db: DatabaseInfo, projectRoot?: string): Promise<Record<string, unknown> | null>;
334
+ export declare function loadSchema(db: DatabaseInfo, projectRoot?: string): Promise<Record<string, unknown> | null>;
329
335
  /**
330
336
  * Diff a schema against the production snapshot in migrationsDir.
331
337
  * Returns whether there are changes, the SQL statements, and both snapshots.
332
338
  */
333
- declare function diffSchema(schema: Record<string, unknown>, migrationsDir: string): Promise<DiffResult>;
339
+ export declare function diffSchema(schema: Record<string, unknown>, migrationsDir: string): Promise<DiffResult>;
334
340
  //#endregion
335
- export { type DatabaseDevState, type DatabaseStatus, type DevPaths, type DevState, type DiffResult, type DiscoverOptions, type GenerateContext, type GenerateOptions, type GenerateResult, type PushContext, type PushResult, type ResetContext, type ResetOptions, type ResetResult, type StatusContext, type StatusResult, type ValidateContext, type ValidateError, type ValidateResult, createDbCommand, diffSchema, discoverDatabases, formatStatus, generate, generateEpoch, generateOne, getDevEpoch, getDevPaths, getInstanceKey, loadDevMigrations, loadDevState, loadSchema, push, pushOne, registerDbCommands, reportCliError, reset, resetAndPush, saveDevState, status, validate };
341
+ export type { DatabaseDevState, DatabaseSource, DatabaseStatus, DbCommandDefaults, DevPaths, DevState, DiffResult, DiscoverOptions, GenerateContext, GenerateOptions, GenerateResult, PushContext, PushResult, ResetContext, ResetOptions, ResetResult, StatusContext, StatusResult, ValidateContext, ValidateError, ValidateResult };
package/dist/cli/index.js CHANGED
@@ -1,9 +1,4 @@
1
- import "../debug-DmBrUmwe.js";
2
- import { _ as saveDevState, a as generateEpoch, c as getDevPaths, f as loadDevMigrations, l as getInstanceKey, m as loadDevState, s as getDevEpoch } from "../state-DtZ70cBR.js";
3
- import "../snapshot-DMW6j2Ix.js";
4
- import "../generator-KHBZaOI1.js";
5
- import "../parser-CL3Nlmsy.js";
6
- import { a as loadSchema, i as discoverDatabases, n as pushOne, o as reportCliError, r as diffSchema, t as push } from "../push-DiHH52-G.js";
7
- import { a as resetAndPush, c as generate, i as reset, l as generateOne, n as registerDbCommands, o as formatStatus, r as validate, s as status, t as createDbCommand } from "../cli-m2H7mQpa.js";
8
-
9
- export { createDbCommand, diffSchema, discoverDatabases, formatStatus, generate, generateEpoch, generateOne, getDevEpoch, getDevPaths, getInstanceKey, loadDevMigrations, loadDevState, loadSchema, push, pushOne, registerDbCommands, reportCliError, reset, resetAndPush, saveDevState, status, validate };
1
+ import { a as getDevPaths, c as loadDevMigrations, d as saveDevState, i as getDevEpoch, l as loadDevState, o as getInstanceKey, r as generateEpoch, s as init_state } from "../state-OVuoHRC9.js";
2
+ import { a as resetAndPush, c as generate, d as pushOne, f as diffSchema, h as reportCliError, i as reset, l as generateOne, m as loadSchema, n as registerDbCommands, o as formatStatus, p as discoverDatabases, r as validate, s as status, t as createDbCommand, u as push } from "../cli-BUSZTS2D.js";
3
+ init_state();
4
+ export { createDbCommand, diffSchema, discoverDatabases, formatStatus, generate, generateEpoch, generateOne, getDevEpoch, getDevPaths, getInstanceKey, loadDevMigrations, loadDevState, loadSchema, push, pushOne, registerDbCommands, reportCliError, reset, resetAndPush, saveDevState, status, validate };
@@ -1,13 +1,195 @@
1
- import { i as init_debug, t as debugCli } from "./debug-DmBrUmwe.js";
2
- import { _ as saveDevState, a as generateEpoch, c as getDevPaths, d as init_state, f as loadDevMigrations, m as loadDevState, t as clearDatabaseDevState } from "./state-DtZ70cBR.js";
3
- import { a as hashSnapshot } from "./snapshot-DMW6j2Ix.js";
4
- import { a as loadMigrationFiles, i as generateMigrationName, l as saveSnapshot, n as generateCreateTableSQL, s as loadSnapshot, t as buildAndLoadSchema } from "./generator-KHBZaOI1.js";
5
- import { o as resolveImportPath, s as loadViteAliases } from "./parser-CL3Nlmsy.js";
6
- import { a as loadSchema, i as discoverDatabases, o as reportCliError, r as diffSchema, t as push } from "./push-DiHH52-G.js";
1
+ import { i as init_debug, o as __exportAll, t as debugCli } from "./debug-Cz8KzMft.js";
2
+ import { a as getDevPaths, c as loadDevMigrations, d as saveDevState, l as loadDevState, n as clearDevMigrations, r as generateEpoch, s as init_state, t as clearDatabaseDevState, u as saveDevMigration } from "./state-OVuoHRC9.js";
3
+ import { generateMigrationStatements, generateSnapshotFromSchema, hashSnapshot, snapshotsEqual } from "./migrations/snapshot.js";
4
+ import { buildAndLoadSchema, generateCreateTableSQL, generateMigrationName, loadMigrationFiles, loadSnapshot, saveSnapshot } from "./migrations/generator.js";
5
+ import { a as discoverDatabaseFiles, c as loadViteAliases, n as parseDatabaseFile, o as readFile, s as resolveImportPath } from "./parser-DR57GOjv.js";
7
6
  import * as fs from "node:fs";
8
7
  import * as path$1 from "node:path";
9
8
  import { Command } from "commander";
10
-
9
+ import * as crypto from "node:crypto";
10
+ //#region src/cli/shared.ts
11
+ init_state();
12
+ init_debug();
13
+ /**
14
+ * Print a caught error to stderr. Always shows the message; when verbose
15
+ * (flag or `DEBUG=*`) is set, also prints the stack so users can diagnose
16
+ * unexpected failures without patching the CLI.
17
+ */
18
+ function reportCliError(error, verbose = false) {
19
+ const showStack = verbose || Boolean(process.env.DEBUG);
20
+ if (error instanceof Error) {
21
+ console.error("Error:", error.message);
22
+ if (showStack && error.stack) console.error(error.stack);
23
+ return;
24
+ }
25
+ console.error("Error:", error);
26
+ }
27
+ /**
28
+ * Discover database files, parse them, and resolve migrationsDir.
29
+ * Returns parsed DatabaseInfo[] with migrationsDir already set.
30
+ */
31
+ function discoverDatabases(opts) {
32
+ const { projectRoot, databasesDir, migrationsDir, database } = opts;
33
+ const files = discoverDatabaseFiles({
34
+ projectRoot,
35
+ databasesDir
36
+ });
37
+ const databases = [];
38
+ for (const file of files) {
39
+ const code = readFile(file.absolutePath);
40
+ const parsed = parseDatabaseFile(file.absolutePath, code, { namePrefix: file.prefix });
41
+ if (!parsed.database) continue;
42
+ if (database && parsed.database.name !== database) continue;
43
+ parsed.database.migrationsDir = path$1.resolve(projectRoot, migrationsDir, parsed.database.name);
44
+ databases.push(parsed.database);
45
+ }
46
+ return databases;
47
+ }
48
+ /**
49
+ * Load and validate schema for a database.
50
+ *
51
+ * Returns null only when the database genuinely declares no schema tables.
52
+ * Every other failure mode (inline tables, unresolvable import, build error,
53
+ * missing exports) throws — silently skipping a database is how a typo in
54
+ * schema.ts becomes "why is my migration empty" 20 minutes later, or worse,
55
+ * a generated migration that DROPs tables that still exist in production.
56
+ *
57
+ * `projectRoot` enables alias resolution for non-relative schema imports
58
+ * (e.g. `@/databases/schema`): the project's Vite `resolve.alias` is loaded
59
+ * (cached) and used as the source of truth. Omit it to resolve relative
60
+ * imports only.
61
+ */
62
+ async function loadSchema(db, projectRoot) {
63
+ if (db.schemaTableNames.length === 0) {
64
+ debugCli("Skipping %s: no schema defined", db.name);
65
+ return null;
66
+ }
67
+ if (!db.schemaImport) throw new Error(`[db] Database '${db.name}' declares ${db.schemaTableNames.length} schema table(s) (${db.schemaTableNames.join(", ")}) but none of them are imported from a schema module. Tables defined inline in ${path$1.basename(db.filePath)} cannot be loaded for migration generation — move them to a schema file (e.g. src/databases/schema.ts) and import them.`);
68
+ const aliases = projectRoot ? await loadViteAliases(projectRoot) : void 0;
69
+ const schemaPath = resolveImportPath(db.filePath, db.schemaImport, aliases);
70
+ if (!schemaPath) throw new Error(`[db] Database '${db.name}': could not resolve schema import '${db.schemaImport}' from ${db.filePath}.` + (db.schemaImport.startsWith(".") ? "" : ` '${db.schemaImport}' looks like an alias — ensure it's defined in the project's Vite config (resolve.alias / tsconfig paths wired into Vite).`));
71
+ let schema;
72
+ try {
73
+ schema = await buildAndLoadSchema(schemaPath, db.schemaTableNames);
74
+ } catch (error) {
75
+ const message = error instanceof Error ? error.message : String(error);
76
+ debugCli("Failed to load schema for %s: %O", db.name, error);
77
+ throw new Error(`[db] Could not build schema for database '${db.name}' (${schemaPath}): ${message}`, { cause: error });
78
+ }
79
+ const missing = db.schemaTableNames.filter((name) => !(name in schema));
80
+ if (missing.length > 0) throw new Error(`[db] Database '${db.name}': schema module ${schemaPath} does not export: ${missing.join(", ")}. Every table referenced in defineDatabase({ schema }) must be exported from the same schema module.`);
81
+ return schema;
82
+ }
83
+ /**
84
+ * Diff a schema against the production snapshot in migrationsDir.
85
+ * Returns whether there are changes, the SQL statements, and both snapshots.
86
+ */
87
+ async function diffSchema(schema, migrationsDir) {
88
+ const prodSnapshot = loadSnapshot(migrationsDir);
89
+ const currentSnapshot = await generateSnapshotFromSchema(schema);
90
+ if (snapshotsEqual(prodSnapshot, currentSnapshot)) return {
91
+ hasChanges: false,
92
+ statements: [],
93
+ prodSnapshot,
94
+ currentSnapshot
95
+ };
96
+ const statements = await generateMigrationStatements(prodSnapshot, currentSnapshot);
97
+ return {
98
+ hasChanges: statements.length > 0,
99
+ statements,
100
+ prodSnapshot,
101
+ currentSnapshot
102
+ };
103
+ }
104
+ //#endregion
105
+ //#region src/cli/push.ts
106
+ var push_exports = /* @__PURE__ */ __exportAll({
107
+ push: () => push,
108
+ pushOne: () => pushOne
109
+ });
110
+ init_debug();
111
+ /**
112
+ * Push schema changes to dev migrations
113
+ *
114
+ * This command:
115
+ * 1. Discovers all databases in the project
116
+ * 2. For each database, diffs production snapshot against current schema
117
+ * 3. If changes detected, generates a single squashed dev migration
118
+ * 4. Uses content-hash naming so the same schema always produces the same
119
+ * migration name — the DO skips it if already applied
120
+ *
121
+ * Dev migrations are stored in node_modules/.cache/durable-db/
122
+ * and are ephemeral - they're cleared when running `db:generate` or `db:reset`
123
+ */
124
+ async function push(ctx = {}) {
125
+ const { projectRoot = process.cwd(), databasesDir = "src/databases", migrationsDir = "migrations" } = ctx;
126
+ const results = [];
127
+ const databases = discoverDatabases({
128
+ projectRoot,
129
+ databasesDir,
130
+ migrationsDir
131
+ });
132
+ if (databases.length === 0) {
133
+ debugCli("No databases found");
134
+ return results;
135
+ }
136
+ for (const db of databases) {
137
+ const result = await pushDatabase(projectRoot, db);
138
+ results.push(result);
139
+ }
140
+ return results;
141
+ }
142
+ /**
143
+ * Push a single database
144
+ *
145
+ * Always diffs from the production snapshot to the current schema,
146
+ * producing a single squashed dev migration with a deterministic
147
+ * content-hash name.
148
+ */
149
+ async function pushDatabase(projectRoot, db) {
150
+ const result = {
151
+ database: db.name,
152
+ hasChanges: false,
153
+ statements: [],
154
+ migrationName: null
155
+ };
156
+ const schema = await loadSchema(db, projectRoot);
157
+ if (!schema) return result;
158
+ const diff = await diffSchema(schema, db.migrationsDir);
159
+ if (!diff.hasChanges) {
160
+ debugCli("No changes for %s", db.name);
161
+ return result;
162
+ }
163
+ const safeStatements = diff.statements.map((s) => s.replace(/\bCREATE TABLE\b(?!\s+IF\s+NOT\s+EXISTS)/gi, "CREATE TABLE IF NOT EXISTS").replace(/\bCREATE INDEX\b(?!\s+IF\s+NOT\s+EXISTS)/gi, "CREATE INDEX IF NOT EXISTS").replace(/\bCREATE UNIQUE INDEX\b(?!\s+IF\s+NOT\s+EXISTS)/gi, "CREATE UNIQUE INDEX IF NOT EXISTS"));
164
+ const migrationName = `dev_${crypto.createHash("sha256").update(safeStatements.join("\n")).digest("hex").slice(0, 8)}`;
165
+ if (loadDevMigrations(projectRoot, db.name).has(migrationName)) {
166
+ debugCli("Migration %s already exists for %s, skipping", migrationName, db.name);
167
+ return result;
168
+ }
169
+ clearDevMigrations(projectRoot, db.name);
170
+ saveDevMigration(projectRoot, db.name, migrationName, safeStatements);
171
+ result.hasChanges = true;
172
+ result.statements = diff.statements;
173
+ result.migrationName = migrationName;
174
+ debugCli("Generated %s for %s (%d statements)", migrationName, db.name, diff.statements.length);
175
+ return result;
176
+ }
177
+ /**
178
+ * Push a single database by name
179
+ * Useful when you only want to push one specific database
180
+ */
181
+ async function pushOne(ctx = {}, dbName) {
182
+ const { projectRoot = process.cwd(), databasesDir = "src/databases", migrationsDir = "migrations" } = ctx;
183
+ const databases = discoverDatabases({
184
+ projectRoot,
185
+ databasesDir,
186
+ migrationsDir,
187
+ database: dbName
188
+ });
189
+ if (databases.length === 0) return null;
190
+ return await pushDatabase(projectRoot, databases[0]);
191
+ }
192
+ //#endregion
11
193
  //#region src/cli/generate.ts
12
194
  init_state();
13
195
  init_debug();
@@ -96,7 +278,6 @@ async function generateOne(ctx, dbName, options = {}) {
96
278
  });
97
279
  return results.length > 0 ? results[0] : null;
98
280
  }
99
-
100
281
  //#endregion
101
282
  //#region src/cli/status.ts
102
283
  init_state();
@@ -150,7 +331,8 @@ async function getDatabaseStatus(projectRoot, db, devState) {
150
331
  dbStatus.devMigrationCount = loadDevMigrations(projectRoot, db.name).size;
151
332
  const schema = await loadSchema(db, projectRoot);
152
333
  if (!schema) return dbStatus;
153
- const prodSnapshotHash = hashSnapshot(loadSnapshot(db.migrationsDir));
334
+ const prodSnapshot = loadSnapshot(db.migrationsDir);
335
+ const prodSnapshotHash = hashSnapshot(prodSnapshot);
154
336
  const dbDevState = devState.databases[db.name];
155
337
  if (dbDevState && dbDevState.prodSnapshotHash !== prodSnapshotHash) dbStatus.prodSnapshotChanged = true;
156
338
  try {
@@ -196,7 +378,6 @@ function formatStatus(result) {
196
378
  }
197
379
  return lines.join("\n");
198
380
  }
199
-
200
381
  //#endregion
201
382
  //#region src/cli/reset.ts
202
383
  init_state();
@@ -322,13 +503,12 @@ async function reset(ctx = {}, options = {}) {
322
503
  * Convenience function that combines reset + push
323
504
  */
324
505
  async function resetAndPush(ctx = {}, options = {}) {
325
- const { push: push$1 } = await import("./push-BY3lfh-R.js");
506
+ const { push } = await Promise.resolve().then(() => push_exports);
326
507
  return {
327
508
  reset: await reset(ctx, options),
328
- push: await push$1(ctx)
509
+ push: await push(ctx)
329
510
  };
330
511
  }
331
-
332
512
  //#endregion
333
513
  //#region src/cli/validate.ts
334
514
  init_state();
@@ -561,28 +741,17 @@ async function validateDatabase(db, opts) {
561
741
  }
562
742
  return result;
563
743
  }
564
-
565
744
  //#endregion
566
745
  //#region src/cli/command.ts
567
- /**
568
- * Register all database subcommands (push, generate, status, reset,
569
- * validate) directly on the given Commander command.
570
- *
571
- * Use this to flatten the commands onto your own program — the standalone
572
- * `db` binary does this so `db push` works without a nested group:
573
- *
574
- * registerDbCommands(program); // → `mycli push`
575
- *
576
- * Or use {@link createDbCommand} to mount them as a `db` group:
577
- *
578
- * program.addCommand(createDbCommand()); // → `mycli db push`
579
- */
580
- function registerDbCommands(program) {
581
- program.command("push").description("Push schema changes to dev migrations").option("-d, --databases-dir <dir>", "Directory containing databases", "src/databases").option("-m, --migrations-dir <dir>", "Directory for production migrations", "migrations").option("-v, --verbose", "Verbose output").action(async (options) => {
746
+ function registerDbCommands(program, defaults = {}) {
747
+ const dirs = (options) => ({
748
+ databasesDir: options.databasesDir ?? defaults.databasesDir ?? "src/databases",
749
+ migrationsDir: options.migrationsDir ?? defaults.migrationsDir ?? "migrations"
750
+ });
751
+ program.command("push").description("Push schema changes to dev migrations").option("-d, --databases-dir <dir>", "Directory containing databases (default: src/databases)").option("-m, --migrations-dir <dir>", "Directory for production migrations (default: migrations)").option("-v, --verbose", "Verbose output").action(async (options) => {
582
752
  try {
583
753
  const results = await push({
584
- databasesDir: options.databasesDir,
585
- migrationsDir: options.migrationsDir,
754
+ ...dirs(options),
586
755
  verbose: options.verbose
587
756
  });
588
757
  if (results.length === 0) {
@@ -600,11 +769,10 @@ function registerDbCommands(program) {
600
769
  process.exit(1);
601
770
  }
602
771
  });
603
- program.command("generate [name]").description("Generate production migration from schema changes").option("--database <db>", "Only generate for this database").option("-d, --databases-dir <dir>", "Directory containing databases", "src/databases").option("-m, --migrations-dir <dir>", "Directory for production migrations", "migrations").option("-v, --verbose", "Verbose output").action(async (name, options) => {
772
+ program.command("generate [name]").description("Generate production migration from schema changes").option("--database <db>", "Only generate for this database").option("-d, --databases-dir <dir>", "Directory containing databases (default: src/databases)").option("-m, --migrations-dir <dir>", "Directory for production migrations (default: migrations)").option("-v, --verbose", "Verbose output").action(async (name, options) => {
604
773
  try {
605
774
  const results = await generate({
606
- databasesDir: options.databasesDir,
607
- migrationsDir: options.migrationsDir,
775
+ ...dirs(options),
608
776
  verbose: options.verbose
609
777
  }, {
610
778
  name,
@@ -627,11 +795,10 @@ function registerDbCommands(program) {
627
795
  process.exit(1);
628
796
  }
629
797
  });
630
- program.command("status").description("Show database migration status").option("-d, --databases-dir <dir>", "Directory containing databases", "src/databases").option("-m, --migrations-dir <dir>", "Directory for production migrations", "migrations").option("-v, --verbose", "Verbose output").action(async (options) => {
798
+ program.command("status").description("Show database migration status").option("-d, --databases-dir <dir>", "Directory containing databases (default: src/databases)").option("-m, --migrations-dir <dir>", "Directory for production migrations (default: migrations)").option("-v, --verbose", "Verbose output").action(async (options) => {
631
799
  try {
632
800
  const result = await status({
633
- databasesDir: options.databasesDir,
634
- migrationsDir: options.migrationsDir,
801
+ ...dirs(options),
635
802
  verbose: options.verbose
636
803
  });
637
804
  console.log(formatStatus(result));
@@ -640,10 +807,10 @@ function registerDbCommands(program) {
640
807
  process.exit(1);
641
808
  }
642
809
  });
643
- program.command("reset").description("Reset dev state and create fresh DB instances (via epoch bump)").option("--keep-epoch", "Only clear dev migrations, keep the same epoch").option("--purge-local-storage", "Also delete workerd's persisted DO storage under .wrangler/ (requires the dev server to be stopped)").option("--database <db>", "Only reset this database").option("-d, --databases-dir <dir>", "Directory containing databases", "src/databases").option("-m, --migrations-dir <dir>", "Directory for production migrations", "migrations").option("-v, --verbose", "Verbose output").action(async (options) => {
810
+ program.command("reset").description("Reset dev state and create fresh DB instances (via epoch bump)").option("--keep-epoch", "Only clear dev migrations, keep the same epoch").option("--purge-local-storage", "Also delete workerd's persisted DO storage under .wrangler/ (requires the dev server to be stopped)").option("--database <db>", "Only reset this database").option("-d, --databases-dir <dir>", "Directory containing databases (default: src/databases)").option("-m, --migrations-dir <dir>", "Directory for production migrations (default: migrations)").option("-v, --verbose", "Verbose output").action(async (options) => {
644
811
  try {
645
812
  const result = await reset({
646
- databasesDir: options.databasesDir,
813
+ databasesDir: dirs(options).databasesDir,
647
814
  verbose: options.verbose
648
815
  }, {
649
816
  keepEpoch: options.keepEpoch,
@@ -663,11 +830,10 @@ function registerDbCommands(program) {
663
830
  process.exit(1);
664
831
  }
665
832
  });
666
- program.command("validate").description("Dry-run migrations against local SQLite to catch errors before deployment").option("--database <db>", "Only validate this database").option("--no-dev", "Skip dev migrations, only validate production").option("-d, --databases-dir <dir>", "Directory containing databases", "src/databases").option("-m, --migrations-dir <dir>", "Directory for production migrations", "migrations").option("-v, --verbose", "Show each migration as it is applied").action(async (options) => {
833
+ program.command("validate").description("Dry-run migrations against local SQLite to catch errors before deployment").option("--database <db>", "Only validate this database").option("--no-dev", "Skip dev migrations, only validate production").option("-d, --databases-dir <dir>", "Directory containing databases (default: src/databases)").option("-m, --migrations-dir <dir>", "Directory for production migrations (default: migrations)").option("-v, --verbose", "Show each migration as it is applied").action(async (options) => {
667
834
  try {
668
835
  const results = await validate({
669
- databasesDir: options.databasesDir,
670
- migrationsDir: options.migrationsDir,
836
+ ...dirs(options),
671
837
  verbose: options.verbose,
672
838
  noDev: !options.dev,
673
839
  database: options.database
@@ -678,9 +844,9 @@ function registerDbCommands(program) {
678
844
  }
679
845
  let allValid = true;
680
846
  for (const r of results) {
681
- const status$1 = r.migrationsValid ? "✓" : "✗";
847
+ const status = r.migrationsValid ? "✓" : "✗";
682
848
  const devNote = r.includesDevMigrations ? " (includes dev migrations)" : "";
683
- console.log(`${status$1} ${r.database}: ${r.migrationCount} migration(s)${devNote}`);
849
+ console.log(`${status} ${r.database}: ${r.migrationCount} migration(s)${devNote}`);
684
850
  if (!r.migrationsValid) {
685
851
  allValid = false;
686
852
  for (const err of r.errors) {
@@ -708,13 +874,11 @@ function registerDbCommands(program) {
708
874
  * `program.addCommand(createDbCommand())` so the commands live under a
709
875
  * `db` prefix (e.g. `mycli db push`).
710
876
  */
711
- function createDbCommand() {
712
- return registerDbCommands(new Command("db").description("Database migration management"));
877
+ function createDbCommand(defaults = {}) {
878
+ return registerDbCommands(new Command("db").description("Database migration management"), defaults);
713
879
  }
714
-
715
880
  //#endregion
716
881
  //#region src/cli/index.ts
717
882
  init_state();
718
-
719
883
  //#endregion
720
- export { resetAndPush as a, generate as c, reset as i, generateOne as l, registerDbCommands as n, formatStatus as o, validate as r, status as s, createDbCommand as t };
884
+ export { resetAndPush as a, generate as c, pushOne as d, diffSchema as f, reportCliError as h, reset as i, generateOne as l, loadSchema as m, registerDbCommands as n, formatStatus as o, discoverDatabases as p, validate as r, status as s, createDbCommand as t, push as u };