durable-db 0.2.0 → 0.2.2
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/{arktypeConfig-zgI5p6zF.d.ts → arktypeConfig-AXvobTPL.d.ts} +0 -1
- package/dist/{arktypeConfig-CTCJm4vA.js → arktypeConfig-DxP0OcV_.js} +1014 -1033
- package/dist/cli/bin.d.ts +1 -1
- package/dist/cli/bin.js +2 -10
- package/dist/cli/index.d.ts +27 -29
- package/dist/cli/index.js +4 -9
- package/dist/{cli-DnsOTcrH.js → cli-BUSZTS2D.js} +196 -19
- package/dist/context/index.d.ts +50 -2
- package/dist/context/index.js +119 -5
- package/dist/db/index.d.ts +4 -4
- package/dist/db/index.js +10 -12
- package/dist/{debug-DmBrUmwe.js → debug-Cz8KzMft.js} +23 -27
- package/dist/{defineDatabase-BD3k1L7d.js → defineDatabase-CHmzpzFf.js} +2 -4
- package/dist/{defineDatabase-DtkM6k1S.d.ts → defineDatabase-IUthY3Ex.d.ts} +5 -5
- package/dist/{discovery-DfimBbS_.d.ts → discovery-gHeLq8jk.d.ts} +1 -1
- package/dist/{index-BHLOQ7uV.d.ts → index-BdrcuAU7.d.ts} +4 -3
- package/dist/index.d.ts +4 -4
- package/dist/index.js +5 -8
- package/dist/{kysely-BH7QZBZw.js → kysely-Be6KwFZC.js} +45 -31
- package/dist/migrations/generator.d.ts +14 -17
- package/dist/migrations/generator.js +202 -5
- package/dist/migrations/snapshot.d.ts +1 -1
- package/dist/migrations/snapshot.js +91 -3
- package/dist/{parser-BdV7Zqcv.js → parser-DR57GOjv.js} +21 -19
- package/dist/registry.d.ts +10 -11
- package/dist/registry.js +3 -5
- package/dist/schema.d.ts +5 -2
- package/dist/schema.js +6 -3
- package/dist/snapshot-CaG5xnE2.d.ts +48 -0
- package/dist/{state-DtZ70cBR.js → state-OVuoHRC9.js} +3 -5
- package/dist/testing/index.d.ts +4 -5
- package/dist/testing/index.js +6 -10
- package/dist/transport/protocol.d.ts +7 -8
- package/dist/transport/protocol.js +34 -3
- package/dist/transport/websocket.d.ts +4 -5
- package/dist/transport/websocket.js +103 -3
- package/dist/vite/durableDb.d.ts +6 -7
- package/dist/vite/durableDb.js +23 -28
- package/package.json +12 -12
- package/dist/context-kIVZbhye.js +0 -121
- package/dist/generator-KHBZaOI1.js +0 -202
- package/dist/index-zzQS_psa.d.ts +0 -51
- package/dist/protocol-DEubbBbR.js +0 -35
- package/dist/push-BhrMZaQx.js +0 -190
- package/dist/push-cUJBpv5y.js +0 -8
- package/dist/schema-C2yy5KCT.d.ts +0 -6
- package/dist/schema-IFq7ovQq.js +0 -8
- package/dist/snapshot-DMW6j2Ix.js +0 -93
- package/dist/snapshot-DsSRYFe-.d.ts +0 -125
- package/dist/state-vav3VCId.js +0 -5
- 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 "../
|
|
3
|
-
import "../state-DtZ70cBR.js";
|
|
4
|
-
import "../snapshot-DMW6j2Ix.js";
|
|
5
|
-
import "../generator-KHBZaOI1.js";
|
|
6
|
-
import "../parser-BdV7Zqcv.js";
|
|
7
|
-
import "../push-BhrMZaQx.js";
|
|
8
|
-
import { n as registerDbCommands } from "../cli-DnsOTcrH.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 {};
|
package/dist/cli/index.d.ts
CHANGED
|
@@ -1,11 +1,9 @@
|
|
|
1
|
-
import { t as DatabaseSource } from "../discovery-
|
|
2
|
-
import { t as Snapshot } from "../snapshot-
|
|
3
|
-
import { l as DatabaseInfo } from "../defineDatabase-
|
|
4
|
-
import "../index-
|
|
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-IUthY3Ex.js";
|
|
4
|
+
import "../index-BdrcuAU7.js";
|
|
5
5
|
import { Command } from "commander";
|
|
6
|
-
|
|
7
6
|
//#region src/cli/command.d.ts
|
|
8
|
-
|
|
9
7
|
/**
|
|
10
8
|
* Register all database subcommands (push, generate, status, reset,
|
|
11
9
|
* validate) directly on the given Commander command.
|
|
@@ -25,14 +23,14 @@ interface DbCommandDefaults {
|
|
|
25
23
|
/** Where production migrations live when `-m` is not given (default `migrations`). */
|
|
26
24
|
migrationsDir?: string;
|
|
27
25
|
}
|
|
28
|
-
declare function registerDbCommands(program: Command, defaults?: DbCommandDefaults): Command;
|
|
26
|
+
export declare function registerDbCommands(program: Command, defaults?: DbCommandDefaults): Command;
|
|
29
27
|
/**
|
|
30
28
|
* Create a Commander command group named `db` with all database
|
|
31
29
|
* subcommands. Mount it in a host CLI with
|
|
32
30
|
* `program.addCommand(createDbCommand())` so the commands live under a
|
|
33
31
|
* `db` prefix (e.g. `mycli db push`).
|
|
34
32
|
*/
|
|
35
|
-
declare function createDbCommand(defaults?: DbCommandDefaults): Command;
|
|
33
|
+
export declare function createDbCommand(defaults?: DbCommandDefaults): Command;
|
|
36
34
|
//#endregion
|
|
37
35
|
//#region src/cli/state.d.ts
|
|
38
36
|
interface DatabaseDevState {
|
|
@@ -62,32 +60,32 @@ interface DevPaths {
|
|
|
62
60
|
/**
|
|
63
61
|
* Get all dev-related paths for a project
|
|
64
62
|
*/
|
|
65
|
-
declare function getDevPaths(projectRoot: string): DevPaths;
|
|
63
|
+
export declare function getDevPaths(projectRoot: string): DevPaths;
|
|
66
64
|
/**
|
|
67
65
|
* Generate a new epoch value (timestamp-based)
|
|
68
66
|
*/
|
|
69
|
-
declare function generateEpoch(): string;
|
|
67
|
+
export declare function generateEpoch(): string;
|
|
70
68
|
/**
|
|
71
69
|
* Load the dev state from disk
|
|
72
70
|
*/
|
|
73
|
-
declare function loadDevState(projectRoot: string): DevState;
|
|
71
|
+
export declare function loadDevState(projectRoot: string): DevState;
|
|
74
72
|
/**
|
|
75
73
|
* Save the dev state to disk
|
|
76
74
|
*/
|
|
77
|
-
declare function saveDevState(projectRoot: string, state: DevState): void;
|
|
75
|
+
export declare function saveDevState(projectRoot: string, state: DevState): void;
|
|
78
76
|
/**
|
|
79
77
|
* Load dev migrations for a database
|
|
80
78
|
*/
|
|
81
|
-
declare function loadDevMigrations(projectRoot: string, dbName: string): Map<string, string[][]>;
|
|
79
|
+
export declare function loadDevMigrations(projectRoot: string, dbName: string): Map<string, string[][]>;
|
|
82
80
|
/**
|
|
83
81
|
* Get the dev epoch for instance key suffixing
|
|
84
82
|
* Returns null in production or if no dev state exists
|
|
85
83
|
*/
|
|
86
|
-
declare function getDevEpoch(projectRoot: string): string | null;
|
|
84
|
+
export declare function getDevEpoch(projectRoot: string): string | null;
|
|
87
85
|
/**
|
|
88
86
|
* Get a database instance key with optional dev epoch suffix
|
|
89
87
|
*/
|
|
90
|
-
declare function getInstanceKey(baseKey: string, epoch: string | null): string;
|
|
88
|
+
export declare function getInstanceKey(baseKey: string, epoch: string | null): string;
|
|
91
89
|
//#endregion
|
|
92
90
|
//#region src/cli/push.d.ts
|
|
93
91
|
interface PushContext {
|
|
@@ -115,12 +113,12 @@ interface PushResult {
|
|
|
115
113
|
* Dev migrations are stored in node_modules/.cache/durable-db/
|
|
116
114
|
* and are ephemeral - they're cleared when running `db:generate` or `db:reset`
|
|
117
115
|
*/
|
|
118
|
-
declare function push(ctx?: PushContext): Promise<PushResult[]>;
|
|
116
|
+
export declare function push(ctx?: PushContext): Promise<PushResult[]>;
|
|
119
117
|
/**
|
|
120
118
|
* Push a single database by name
|
|
121
119
|
* Useful when you only want to push one specific database
|
|
122
120
|
*/
|
|
123
|
-
declare function pushOne(ctx: PushContext | undefined, dbName: string): Promise<PushResult | null>;
|
|
121
|
+
export declare function pushOne(ctx: PushContext | undefined, dbName: string): Promise<PushResult | null>;
|
|
124
122
|
//#endregion
|
|
125
123
|
//#region src/cli/generate.d.ts
|
|
126
124
|
interface GenerateContext {
|
|
@@ -154,11 +152,11 @@ interface GenerateResult {
|
|
|
154
152
|
* Unlike `push`, this writes to the actual migrations directory
|
|
155
153
|
* that gets committed to git.
|
|
156
154
|
*/
|
|
157
|
-
declare function generate(ctx?: GenerateContext, options?: GenerateOptions): Promise<GenerateResult[]>;
|
|
155
|
+
export declare function generate(ctx?: GenerateContext, options?: GenerateOptions): Promise<GenerateResult[]>;
|
|
158
156
|
/**
|
|
159
157
|
* Generate migration for a single database by name
|
|
160
158
|
*/
|
|
161
|
-
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>;
|
|
162
160
|
//#endregion
|
|
163
161
|
//#region src/cli/reset.d.ts
|
|
164
162
|
interface ResetContext {
|
|
@@ -205,12 +203,12 @@ interface ResetResult {
|
|
|
205
203
|
* - Your local DB is in a broken state
|
|
206
204
|
* - Someone else committed migrations and you pulled
|
|
207
205
|
*/
|
|
208
|
-
declare function reset(ctx?: ResetContext, options?: ResetOptions): Promise<ResetResult>;
|
|
206
|
+
export declare function reset(ctx?: ResetContext, options?: ResetOptions): Promise<ResetResult>;
|
|
209
207
|
/**
|
|
210
208
|
* Reset everything and re-run push
|
|
211
209
|
* Convenience function that combines reset + push
|
|
212
210
|
*/
|
|
213
|
-
declare function resetAndPush(ctx?: ResetContext, options?: ResetOptions): Promise<{
|
|
211
|
+
export declare function resetAndPush(ctx?: ResetContext, options?: ResetOptions): Promise<{
|
|
214
212
|
reset: ResetResult;
|
|
215
213
|
push: PushResult[];
|
|
216
214
|
}>;
|
|
@@ -254,11 +252,11 @@ interface StatusResult {
|
|
|
254
252
|
* - Whether there are uncommitted schema changes
|
|
255
253
|
* - What SQL would be generated
|
|
256
254
|
*/
|
|
257
|
-
declare function status(ctx?: StatusContext): Promise<StatusResult>;
|
|
255
|
+
export declare function status(ctx?: StatusContext): Promise<StatusResult>;
|
|
258
256
|
/**
|
|
259
257
|
* Format status for display
|
|
260
258
|
*/
|
|
261
|
-
declare function formatStatus(result: StatusResult): string;
|
|
259
|
+
export declare function formatStatus(result: StatusResult): string;
|
|
262
260
|
//#endregion
|
|
263
261
|
//#region src/cli/validate.d.ts
|
|
264
262
|
interface ValidateContext {
|
|
@@ -291,7 +289,7 @@ interface ValidateResult {
|
|
|
291
289
|
* before deployment. Optionally compares the migrated schema against a
|
|
292
290
|
* from-scratch schema build (dual-path verification).
|
|
293
291
|
*/
|
|
294
|
-
declare function validate(ctx?: ValidateContext): Promise<ValidateResult[]>;
|
|
292
|
+
export declare function validate(ctx?: ValidateContext): Promise<ValidateResult[]>;
|
|
295
293
|
//#endregion
|
|
296
294
|
//#region src/cli/shared.d.ts
|
|
297
295
|
/**
|
|
@@ -299,7 +297,7 @@ declare function validate(ctx?: ValidateContext): Promise<ValidateResult[]>;
|
|
|
299
297
|
* (flag or `DEBUG=*`) is set, also prints the stack so users can diagnose
|
|
300
298
|
* unexpected failures without patching the CLI.
|
|
301
299
|
*/
|
|
302
|
-
declare function reportCliError(error: unknown, verbose?: boolean): void;
|
|
300
|
+
export declare function reportCliError(error: unknown, verbose?: boolean): void;
|
|
303
301
|
interface DiscoverOptions {
|
|
304
302
|
projectRoot: string;
|
|
305
303
|
/** A directory, or several with name prefixes — see DiscoveryOptions. */
|
|
@@ -318,7 +316,7 @@ interface DiffResult {
|
|
|
318
316
|
* Discover database files, parse them, and resolve migrationsDir.
|
|
319
317
|
* Returns parsed DatabaseInfo[] with migrationsDir already set.
|
|
320
318
|
*/
|
|
321
|
-
declare function discoverDatabases(opts: DiscoverOptions): DatabaseInfo[];
|
|
319
|
+
export declare function discoverDatabases(opts: DiscoverOptions): DatabaseInfo[];
|
|
322
320
|
/**
|
|
323
321
|
* Load and validate schema for a database.
|
|
324
322
|
*
|
|
@@ -333,11 +331,11 @@ declare function discoverDatabases(opts: DiscoverOptions): DatabaseInfo[];
|
|
|
333
331
|
* (cached) and used as the source of truth. Omit it to resolve relative
|
|
334
332
|
* imports only.
|
|
335
333
|
*/
|
|
336
|
-
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>;
|
|
337
335
|
/**
|
|
338
336
|
* Diff a schema against the production snapshot in migrationsDir.
|
|
339
337
|
* Returns whether there are changes, the SQL statements, and both snapshots.
|
|
340
338
|
*/
|
|
341
|
-
declare function diffSchema(schema: Record<string, unknown>, migrationsDir: string): Promise<DiffResult>;
|
|
339
|
+
export declare function diffSchema(schema: Record<string, unknown>, migrationsDir: string): Promise<DiffResult>;
|
|
342
340
|
//#endregion
|
|
343
|
-
export {
|
|
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 "../
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
import "../parser-BdV7Zqcv.js";
|
|
6
|
-
import { a as loadSchema, i as discoverDatabases, n as pushOne, o as reportCliError, r as diffSchema, t as push } from "../push-BhrMZaQx.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-DnsOTcrH.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-
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import { c as loadViteAliases, s as resolveImportPath } from "./parser-
|
|
6
|
-
import { a as loadSchema, i as discoverDatabases, o as reportCliError, r as diffSchema, t as push } from "./push-BhrMZaQx.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
|
|
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
|
|
506
|
+
const { push } = await Promise.resolve().then(() => push_exports);
|
|
326
507
|
return {
|
|
327
508
|
reset: await reset(ctx, options),
|
|
328
|
-
push: await push
|
|
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,7 +741,6 @@ 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
746
|
function registerDbCommands(program, defaults = {}) {
|
|
@@ -665,9 +844,9 @@ function registerDbCommands(program, defaults = {}) {
|
|
|
665
844
|
}
|
|
666
845
|
let allValid = true;
|
|
667
846
|
for (const r of results) {
|
|
668
|
-
const status
|
|
847
|
+
const status = r.migrationsValid ? "✓" : "✗";
|
|
669
848
|
const devNote = r.includesDevMigrations ? " (includes dev migrations)" : "";
|
|
670
|
-
console.log(`${status
|
|
849
|
+
console.log(`${status} ${r.database}: ${r.migrationCount} migration(s)${devNote}`);
|
|
671
850
|
if (!r.migrationsValid) {
|
|
672
851
|
allValid = false;
|
|
673
852
|
for (const err of r.errors) {
|
|
@@ -698,10 +877,8 @@ function registerDbCommands(program, defaults = {}) {
|
|
|
698
877
|
function createDbCommand(defaults = {}) {
|
|
699
878
|
return registerDbCommands(new Command("db").description("Database migration management"), defaults);
|
|
700
879
|
}
|
|
701
|
-
|
|
702
880
|
//#endregion
|
|
703
881
|
//#region src/cli/index.ts
|
|
704
882
|
init_state();
|
|
705
|
-
|
|
706
883
|
//#endregion
|
|
707
|
-
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 };
|
package/dist/context/index.d.ts
CHANGED
|
@@ -1,2 +1,50 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
//#region src/context/index.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Configure a tenant ID resolver.
|
|
4
|
+
*
|
|
5
|
+
* The resolver is called at the moment a database operation needs the tenant ID —
|
|
6
|
+
* by which point request middleware (auth, session, etc.) has already completed.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* ```ts
|
|
10
|
+
* import { setTenantIdResolver } from 'durable-db/context';
|
|
11
|
+
* import { getRequestInfo } from 'rwsdk/worker';
|
|
12
|
+
*
|
|
13
|
+
* setTenantIdResolver(() => getRequestInfo().ctx.session!.shop);
|
|
14
|
+
* ```
|
|
15
|
+
*/
|
|
16
|
+
export declare function setTenantIdResolver(resolver: (() => string) | null): void;
|
|
17
|
+
export declare function getTenantId(): string;
|
|
18
|
+
/**
|
|
19
|
+
* Check if a tenant ID resolver is configured (or a Durable Object context
|
|
20
|
+
* can supply the tenant).
|
|
21
|
+
*/
|
|
22
|
+
export declare function hasTenantId(): boolean;
|
|
23
|
+
/**
|
|
24
|
+
* Get the dev epoch for instance key suffixing
|
|
25
|
+
* Only used in development to allow database resets
|
|
26
|
+
*
|
|
27
|
+
* Returns null in production or if no dev state exists
|
|
28
|
+
*
|
|
29
|
+
* @deprecated The epoch is now baked into generated stubs at build time via
|
|
30
|
+
* the `virtual:durable-db/__devEpoch` module — this function
|
|
31
|
+
* cannot read the dev state inside workerd (no filesystem) and returns null
|
|
32
|
+
* there. Import `devEpoch` / `applyDevEpoch` from the virtual module instead.
|
|
33
|
+
*/
|
|
34
|
+
export declare function getDevInstanceKeySuffix(): string | null;
|
|
35
|
+
/**
|
|
36
|
+
* Get a database instance key, optionally suffixed with dev epoch
|
|
37
|
+
*
|
|
38
|
+
* In development, this appends an epoch suffix to enable database resets.
|
|
39
|
+
* In production, this returns the base key unchanged.
|
|
40
|
+
*
|
|
41
|
+
* @deprecated Generated stubs apply the epoch automatically via
|
|
42
|
+
* `applyDevEpoch` from `virtual:durable-db/__devEpoch`. This
|
|
43
|
+
* function only works in Node (it reads the dev state from disk) and is the
|
|
44
|
+
* identity inside workerd — combining it with the generated stubs would
|
|
45
|
+
* also double-suffix keys. Import from the virtual module instead.
|
|
46
|
+
*
|
|
47
|
+
* @param baseKey - The base instance key (e.g., tenant ID or 'global')
|
|
48
|
+
*/
|
|
49
|
+
export declare function getInstanceKey(baseKey: string): string;
|
|
50
|
+
//#endregion
|
package/dist/context/index.js
CHANGED
|
@@ -1,5 +1,119 @@
|
|
|
1
|
-
import "../debug-
|
|
2
|
-
import "../state-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
1
|
+
import { s as __toCommonJS } from "../debug-Cz8KzMft.js";
|
|
2
|
+
import { f as state_exports, s as init_state } from "../state-OVuoHRC9.js";
|
|
3
|
+
//#region src/context/index.ts
|
|
4
|
+
/**
|
|
5
|
+
* Tenant ID resolver for framework integration.
|
|
6
|
+
*/
|
|
7
|
+
let tenantIdResolver = null;
|
|
8
|
+
/**
|
|
9
|
+
* Configure a tenant ID resolver.
|
|
10
|
+
*
|
|
11
|
+
* The resolver is called at the moment a database operation needs the tenant ID —
|
|
12
|
+
* by which point request middleware (auth, session, etc.) has already completed.
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* ```ts
|
|
16
|
+
* import { setTenantIdResolver } from 'durable-db/context';
|
|
17
|
+
* import { getRequestInfo } from 'rwsdk/worker';
|
|
18
|
+
*
|
|
19
|
+
* setTenantIdResolver(() => getRequestInfo().ctx.session!.shop);
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
function setTenantIdResolver(resolver) {
|
|
23
|
+
tenantIdResolver = resolver;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Get the current tenant ID from the configured resolver.
|
|
27
|
+
*
|
|
28
|
+
* @throws Error if no resolver is configured
|
|
29
|
+
*
|
|
30
|
+
* @example
|
|
31
|
+
* ```ts
|
|
32
|
+
* import { getTenantId } from 'durable-db/context';
|
|
33
|
+
*
|
|
34
|
+
* async function myHandler() {
|
|
35
|
+
* const tenantId = getTenantId();
|
|
36
|
+
* // ...
|
|
37
|
+
* }
|
|
38
|
+
* ```
|
|
39
|
+
*/
|
|
40
|
+
/**
|
|
41
|
+
* Inside a Durable Object the instance key IS the tenant (per-tenant DBs key
|
|
42
|
+
* their instances by tenant id, plus an optional `__dev_<epoch>` suffix in
|
|
43
|
+
* dev). The registry publishes its DoContext store getter on globalThis — see
|
|
44
|
+
* the note there for why this is not a module import — so getTenantId() works
|
|
45
|
+
* in action handlers without the worker-side resolver, which the DO execution
|
|
46
|
+
* context never registers.
|
|
47
|
+
*/
|
|
48
|
+
function tenantIdFromDoContext() {
|
|
49
|
+
const getStore = globalThis[Symbol.for("durable-db.doContext")];
|
|
50
|
+
const key = getStore?.()?.instanceKey;
|
|
51
|
+
if (!key || key === "global") return null;
|
|
52
|
+
const suffixAt = key.lastIndexOf("__dev_");
|
|
53
|
+
return suffixAt === -1 ? key : key.slice(0, suffixAt);
|
|
54
|
+
}
|
|
55
|
+
function getTenantId() {
|
|
56
|
+
if (tenantIdResolver) return tenantIdResolver();
|
|
57
|
+
const doTenant = tenantIdFromDoContext();
|
|
58
|
+
if (doTenant) return doTenant;
|
|
59
|
+
throw new Error("getTenantId() called without a resolver. Call setTenantIdResolver() first.");
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Check if a tenant ID resolver is configured (or a Durable Object context
|
|
63
|
+
* can supply the tenant).
|
|
64
|
+
*/
|
|
65
|
+
function hasTenantId() {
|
|
66
|
+
return tenantIdResolver !== null || tenantIdFromDoContext() !== null;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* One-time warning guard: we only log an unexpected dev-epoch load failure
|
|
70
|
+
* once per process so Vite HMR / repeated lookups don't spam stderr.
|
|
71
|
+
*/
|
|
72
|
+
let loggedDevEpochFailure = false;
|
|
73
|
+
/**
|
|
74
|
+
* Get the dev epoch for instance key suffixing
|
|
75
|
+
* Only used in development to allow database resets
|
|
76
|
+
*
|
|
77
|
+
* Returns null in production or if no dev state exists
|
|
78
|
+
*
|
|
79
|
+
* @deprecated The epoch is now baked into generated stubs at build time via
|
|
80
|
+
* the `virtual:durable-db/__devEpoch` module — this function
|
|
81
|
+
* cannot read the dev state inside workerd (no filesystem) and returns null
|
|
82
|
+
* there. Import `devEpoch` / `applyDevEpoch` from the virtual module instead.
|
|
83
|
+
*/
|
|
84
|
+
function getDevInstanceKeySuffix() {
|
|
85
|
+
if (process.env.NODE_ENV === "production") return null;
|
|
86
|
+
try {
|
|
87
|
+
const { getDevEpoch } = (init_state(), __toCommonJS(state_exports));
|
|
88
|
+
return getDevEpoch(process.cwd());
|
|
89
|
+
} catch (e) {
|
|
90
|
+
const code = e?.code;
|
|
91
|
+
if (code !== "MODULE_NOT_FOUND" && code !== "ERR_MODULE_NOT_FOUND" && !loggedDevEpochFailure) {
|
|
92
|
+
loggedDevEpochFailure = true;
|
|
93
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
94
|
+
console.warn(`[durable-db] Could not load dev epoch state (continuing without it): ${message}`);
|
|
95
|
+
}
|
|
96
|
+
return null;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Get a database instance key, optionally suffixed with dev epoch
|
|
101
|
+
*
|
|
102
|
+
* In development, this appends an epoch suffix to enable database resets.
|
|
103
|
+
* In production, this returns the base key unchanged.
|
|
104
|
+
*
|
|
105
|
+
* @deprecated Generated stubs apply the epoch automatically via
|
|
106
|
+
* `applyDevEpoch` from `virtual:durable-db/__devEpoch`. This
|
|
107
|
+
* function only works in Node (it reads the dev state from disk) and is the
|
|
108
|
+
* identity inside workerd — combining it with the generated stubs would
|
|
109
|
+
* also double-suffix keys. Import from the virtual module instead.
|
|
110
|
+
*
|
|
111
|
+
* @param baseKey - The base instance key (e.g., tenant ID or 'global')
|
|
112
|
+
*/
|
|
113
|
+
function getInstanceKey(baseKey) {
|
|
114
|
+
const suffix = getDevInstanceKeySuffix();
|
|
115
|
+
if (!suffix) return baseKey;
|
|
116
|
+
return `${baseKey}__dev_${suffix}`;
|
|
117
|
+
}
|
|
118
|
+
//#endregion
|
|
119
|
+
export { getDevInstanceKeySuffix, getInstanceKey, getTenantId, hasTenantId, setTenantIdResolver };
|