durable-db 0.0.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 (46) hide show
  1. package/README.md +1052 -0
  2. package/dist/cli/bin.d.ts +1 -0
  3. package/dist/cli/bin.js +18 -0
  4. package/dist/cli/index.d.ts +330 -0
  5. package/dist/cli/index.js +9 -0
  6. package/dist/cli-Cr9686BF.js +630 -0
  7. package/dist/context/index.d.ts +2 -0
  8. package/dist/context/index.js +5 -0
  9. package/dist/context-BuIiIQ6K.js +103 -0
  10. package/dist/db/index.d.ts +3 -0
  11. package/dist/db/index.js +760 -0
  12. package/dist/debug-BZJbKybf.js +49 -0
  13. package/dist/defineDatabase-CONf4xFC.js +54 -0
  14. package/dist/defineDatabase-jBv90-Pk.d.ts +188 -0
  15. package/dist/generator-BUPP9scJ.js +180 -0
  16. package/dist/index-BFM5d0FP.d.ts +328 -0
  17. package/dist/index-CqVMaMYY.d.ts +65 -0
  18. package/dist/index.d.ts +6 -0
  19. package/dist/index.js +8 -0
  20. package/dist/migrations/generator.d.ts +101 -0
  21. package/dist/migrations/generator.js +5 -0
  22. package/dist/migrations/snapshot.d.ts +2 -0
  23. package/dist/migrations/snapshot.js +3 -0
  24. package/dist/parser-CbX54Flt.js +293 -0
  25. package/dist/protocol-g_plhPOY.js +35 -0
  26. package/dist/push-BgQ5cnfH.js +184 -0
  27. package/dist/push-BkkaslPd.js +8 -0
  28. package/dist/registry.d.ts +28 -0
  29. package/dist/registry.js +72 -0
  30. package/dist/schema-BOtrGnzM.js +8 -0
  31. package/dist/schema-CpzTOfZ6.d.ts +6 -0
  32. package/dist/schema.d.ts +2 -0
  33. package/dist/schema.js +3 -0
  34. package/dist/snapshot-C162qYoA.d.ts +125 -0
  35. package/dist/snapshot-D170nL7i.js +93 -0
  36. package/dist/state-BCcvNN-M.js +5 -0
  37. package/dist/state-FOEjpgJ6.js +203 -0
  38. package/dist/transport/protocol.d.ts +27 -0
  39. package/dist/transport/protocol.js +3 -0
  40. package/dist/transport/websocket.d.ts +31 -0
  41. package/dist/transport/websocket.js +3 -0
  42. package/dist/vite/durableDb.d.ts +20 -0
  43. package/dist/vite/durableDb.js +933 -0
  44. package/dist/websocket-Dx1fqwnF.js +104 -0
  45. package/package.json +114 -0
  46. package/virtual.d.ts +15 -0
@@ -0,0 +1,49 @@
1
+ import { createRequire } from "node:module";
2
+ import createDebug from "debug";
3
+
4
+ //#region rolldown:runtime
5
+ var __defProp = Object.defineProperty;
6
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7
+ var __getOwnPropNames = Object.getOwnPropertyNames;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __esmMin = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
10
+ var __export = (all, symbols) => {
11
+ let target = {};
12
+ for (var name in all) {
13
+ __defProp(target, name, {
14
+ get: all[name],
15
+ enumerable: true
16
+ });
17
+ }
18
+ if (symbols) {
19
+ __defProp(target, Symbol.toStringTag, { value: "Module" });
20
+ }
21
+ return target;
22
+ };
23
+ var __copyProps = (to, from, except, desc) => {
24
+ if (from && typeof from === "object" || typeof from === "function") {
25
+ for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
26
+ key = keys[i];
27
+ if (!__hasOwnProp.call(to, key) && key !== except) {
28
+ __defProp(to, key, {
29
+ get: ((k) => from[k]).bind(null, key),
30
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
31
+ });
32
+ }
33
+ }
34
+ }
35
+ return to;
36
+ };
37
+ var __toCommonJS = (mod) => __hasOwnProp.call(mod, "module.exports") ? mod["module.exports"] : __copyProps(__defProp({}, "__esModule", { value: true }), mod);
38
+
39
+ //#endregion
40
+ //#region src/utils/debug.ts
41
+ var debugVite, debugCli, debugMigrations;
42
+ var init_debug = __esmMin((() => {
43
+ debugVite = createDebug("database:vite");
44
+ debugCli = createDebug("database:cli");
45
+ debugMigrations = createDebug("database:migrations");
46
+ }));
47
+
48
+ //#endregion
49
+ export { __esmMin as a, init_debug as i, debugMigrations as n, __export as o, debugVite as r, __toCommonJS as s, debugCli as t };
@@ -0,0 +1,54 @@
1
+ import { type } from "arktype";
2
+
3
+ //#region src/db/defineDatabase.ts
4
+ /**
5
+ * Define a database with its schema and migrations.
6
+ *
7
+ * This function is transformed at build time by the durable-db Vite plugin.
8
+ * At runtime, the actions returned will be RPC stubs that call into the
9
+ * generated Durable Object.
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * import { defineDatabase } from 'durable-db';
14
+ * import { users, posts } from './schema';
15
+ *
16
+ * export const { action } = defineDatabase({
17
+ * schema: { users, posts },
18
+ * });
19
+ *
20
+ * export const createUser = action({
21
+ * args: { name: 'string', email: 'string.email' },
22
+ * handler: async (db, args) => {
23
+ * return db.insertInto('users').values({
24
+ * id: crypto.randomUUID(),
25
+ * name: args.name,
26
+ * email: args.email
27
+ * }).returningAll().executeTakeFirst();
28
+ * },
29
+ * });
30
+ * ```
31
+ */
32
+ function defineDatabase(_config) {
33
+ const action = (actionConfig) => {
34
+ const validator = type(actionConfig.args);
35
+ const argKeys = Object.keys(actionConfig.args);
36
+ const argsHint = argKeys.length > 0 ? `args: { ${argKeys.join(", ")} }` : "args: {}";
37
+ const actionFn = async (args) => {
38
+ const result = validator(args);
39
+ if (result instanceof type.errors) throw new Error(`Invalid args for action (${argsHint}): ${result.summary}`);
40
+ throw new Error(`Action (${argsHint}) called without transformation. Make sure the durable-db plugin is configured in your Vite config.`);
41
+ };
42
+ return actionFn;
43
+ };
44
+ const destroyDatabase = async () => {
45
+ throw new Error("destroyDatabase() called without transformation. Make sure the durable-db plugin is configured in your Vite config.");
46
+ };
47
+ return {
48
+ action,
49
+ destroyDatabase
50
+ };
51
+ }
52
+
53
+ //#endregion
54
+ export { defineDatabase as t };
@@ -0,0 +1,188 @@
1
+ import { type } from "arktype";
2
+ import { SQLiteTableWithColumns } from "drizzle-orm/sqlite-core";
3
+ import { Kysely } from "kysely";
4
+ import { Kyselify } from "drizzle-orm/kysely";
5
+
6
+ //#region src/db/types.d.ts
7
+
8
+ /**
9
+ * Base type for ArkType schema definitions.
10
+ * This represents any valid arktype definition object.
11
+ */
12
+ type ArgsSchema = Record<string, unknown>;
13
+ /**
14
+ * Configuration for defineDatabase
15
+ */
16
+ interface DatabaseConfig<TSchema extends Record<string, SQLiteTableWithColumns<any>>> {
17
+ /** Drizzle schema tables */
18
+ schema: TSchema;
19
+ /** Instance strategy - 'per-tenant' (default) or 'global' */
20
+ instance?: 'per-tenant' | 'global';
21
+ /** Enable Outerbase Studio browsable SQL endpoint on this DO.
22
+ * - true: always enabled
23
+ * - false: always disabled (default)
24
+ * - 'development': enabled only in dev mode */
25
+ browsable?: boolean | 'development';
26
+ /** Transport for action stubs: 'rpc' (default) or 'websocket'.
27
+ * WebSocket uses Cloudflare's 20:1 message billing ratio for cheaper high-volume calls. */
28
+ transport?: 'rpc' | 'websocket';
29
+ }
30
+ /**
31
+ * Convert a Drizzle schema to Kysely database types using drizzle-kysely
32
+ */
33
+ type DrizzleToKysely<TSchema extends Record<string, SQLiteTableWithColumns<any>>> = { [K in keyof TSchema]: TSchema[K] extends SQLiteTableWithColumns<any> ? Kyselify<TSchema[K]> : never };
34
+ /**
35
+ * ArkType helpers – mirror Ark's own API:
36
+ * - arkType.validate<Def> → definition shape with DSL validation/autocomplete
37
+ * - arkType.infer<Def> → inferred output type
38
+ */
39
+ type ArkDef<Def> = type.validate<Def>;
40
+ type InferArgs<Def> = type.infer<Def>;
41
+ /**
42
+ * Context passed to action handlers
43
+ */
44
+ interface ActionContext<TEnv = unknown> {
45
+ /** Environment bindings (DO bindings, KV, etc.) */
46
+ env: TEnv;
47
+ /**
48
+ * The instance key used to address this Durable Object.
49
+ * For per-tenant databases, this is the tenant ID.
50
+ * For global databases, this is 'global'.
51
+ */
52
+ instanceKey: string;
53
+ }
54
+ /**
55
+ * Configuration for an action
56
+ *
57
+ * `Def` is "the ArkType definition" – whatever you'd normally pass to `type(...)`:
58
+ * { name: "string", email: "string.email" }
59
+ * unions, tuples, ranges, etc. all work.
60
+ */
61
+ interface ActionConfig<Def, TResult, TSchema extends Record<string, SQLiteTableWithColumns<any>>, TEnv = unknown> {
62
+ /**
63
+ * ArkType definition for args.
64
+ * Typed as `arkType.validate<Def>` so you get the SAME DSL autocomplete
65
+ * as when you do `type(Def)` directly.
66
+ */
67
+ args: ArkDef<Def>;
68
+ /**
69
+ * The action handler
70
+ */
71
+ handler: (db: Kysely<DrizzleToKysely<TSchema>>, args: InferArgs<Def>, ctx: ActionContext<TEnv>) => Promise<TResult>;
72
+ }
73
+ /**
74
+ * An action function that can be called from routes or other actions
75
+ */
76
+ type Action<TArgs, TResult> = (args: TArgs) => Promise<TResult>;
77
+ /**
78
+ * Return type of defineDatabase
79
+ */
80
+ interface DatabaseDefinition<TSchema extends Record<string, SQLiteTableWithColumns<any>>> {
81
+ /**
82
+ * Define an action that runs within the database context
83
+ *
84
+ * NOTE: the `const Def` *here* is crucial – it matches ArkType's own
85
+ * `<const def>(def: type.validate<def>)` pattern and is what makes
86
+ * `"string.email"` etc. behave properly.
87
+ */
88
+ action: <const Def, TResult, TEnv = unknown>(config: ActionConfig<Def, TResult, TSchema, TEnv>) => Action<InferArgs<Def>, TResult>;
89
+ /**
90
+ * Destroy the database instance, clearing all data via `ctx.storage.deleteAll()`.
91
+ * The next action call will re-run migrations and start fresh.
92
+ *
93
+ * For per-tenant databases, targets the current tenant (via `getTenantId()`).
94
+ * For global databases, targets the single shared instance.
95
+ */
96
+ destroyDatabase: () => Promise<void>;
97
+ }
98
+ /**
99
+ * Information about a parsed database file
100
+ */
101
+ interface DatabaseInfo {
102
+ /** File path to the database definition file */
103
+ filePath: string;
104
+ /** Database name derived from filename */
105
+ name: string;
106
+ /** Class name for the Durable Object */
107
+ className: string;
108
+ /** Binding name for wrangler config */
109
+ bindingName: string;
110
+ /** Instance strategy */
111
+ instance: 'per-tenant' | 'global';
112
+ /** Path to migrations directory */
113
+ migrationsDir: string;
114
+ /** Schema import source (relative path) */
115
+ schemaImport: string | null;
116
+ /** Names of schema tables */
117
+ schemaTableNames: string[];
118
+ /** Whether the DO should expose a browsable SQL endpoint */
119
+ browsable: boolean | 'development';
120
+ /** Transport for action stubs */
121
+ transport: 'rpc' | 'websocket';
122
+ /** Loaded migrations - Map of name -> chunks (each chunk is array of SQL statements) */
123
+ migrations?: Map<string, string[][]>;
124
+ }
125
+ /**
126
+ * Information about a parsed action
127
+ */
128
+ interface ActionInfo {
129
+ /** Export name of the action */
130
+ exportName: string;
131
+ /** The args schema (as source code string for codegen) */
132
+ argsSchemaSource: string;
133
+ /** The handler function (as source code string for codegen) */
134
+ handlerSource: string;
135
+ /** The database this action belongs to */
136
+ databaseName: string;
137
+ /** File where the action is defined */
138
+ sourceFile: string;
139
+ }
140
+ /**
141
+ * Result of parsing a database file
142
+ */
143
+ interface ParsedDatabaseFile {
144
+ /** Absolute file path */
145
+ filePath: string;
146
+ /** Database configuration if this file has defineDatabase */
147
+ database: DatabaseInfo | null;
148
+ /** Actions defined in this file */
149
+ actions: ActionInfo[];
150
+ /** Local imports (for dependency resolution) */
151
+ localImports: Map<string, {
152
+ source: string;
153
+ imported: string;
154
+ }>;
155
+ }
156
+ //#endregion
157
+ //#region src/db/defineDatabase.d.ts
158
+ /**
159
+ * Define a database with its schema and migrations.
160
+ *
161
+ * This function is transformed at build time by the durable-db Vite plugin.
162
+ * At runtime, the actions returned will be RPC stubs that call into the
163
+ * generated Durable Object.
164
+ *
165
+ * @example
166
+ * ```ts
167
+ * import { defineDatabase } from 'durable-db';
168
+ * import { users, posts } from './schema';
169
+ *
170
+ * export const { action } = defineDatabase({
171
+ * schema: { users, posts },
172
+ * });
173
+ *
174
+ * export const createUser = action({
175
+ * args: { name: 'string', email: 'string.email' },
176
+ * handler: async (db, args) => {
177
+ * return db.insertInto('users').values({
178
+ * id: crypto.randomUUID(),
179
+ * name: args.name,
180
+ * email: args.email
181
+ * }).returningAll().executeTakeFirst();
182
+ * },
183
+ * });
184
+ * ```
185
+ */
186
+ declare function defineDatabase<TSchema extends Record<string, SQLiteTableWithColumns<any>>>(_config: DatabaseConfig<TSchema>): DatabaseDefinition<TSchema>;
187
+ //#endregion
188
+ export { ActionInfo as a, DatabaseDefinition as c, InferArgs as d, ParsedDatabaseFile as f, ActionContext as i, DatabaseInfo as l, Action as n, ArgsSchema as o, ActionConfig as r, DatabaseConfig as s, defineDatabase as t, DrizzleToKysely as u };
@@ -0,0 +1,180 @@
1
+ import { i as init_debug, n as debugMigrations } from "./debug-BZJbKybf.js";
2
+ import { i as generateSnapshotId, n as generateMigrationStatements, o as snapshotsEqual, r as generateSnapshotFromSchema, t as createEmptySnapshot } from "./snapshot-D170nL7i.js";
3
+ import * as fs from "node:fs";
4
+ import * as path from "node:path";
5
+ import { pathToFileURL } from "node:url";
6
+
7
+ //#region src/migrations/generator.ts
8
+ init_debug();
9
+ /**
10
+ * Snapshot file name
11
+ */
12
+ const SNAPSHOT_FILE = "_snapshot.json";
13
+ /**
14
+ * Load the previous snapshot from the migrations directory
15
+ */
16
+ function loadSnapshot(migrationsDir) {
17
+ const snapshotPath = path.join(migrationsDir, SNAPSHOT_FILE);
18
+ if (!fs.existsSync(snapshotPath)) return createEmptySnapshot();
19
+ const content = fs.readFileSync(snapshotPath, "utf-8");
20
+ try {
21
+ return JSON.parse(content);
22
+ } catch (e) {
23
+ const message = e instanceof Error ? e.message : String(e);
24
+ throw new Error(`[db] Failed to parse snapshot at ${snapshotPath}: ${message}. The file appears corrupt — restore from git, or delete it if you intend to re-derive migrations from scratch (only safe when the migration history matches an empty-starting-point schema).`);
25
+ }
26
+ }
27
+ /**
28
+ * Save a snapshot to the migrations directory
29
+ */
30
+ function saveSnapshot(migrationsDir, snapshot) {
31
+ fs.mkdirSync(migrationsDir, { recursive: true });
32
+ const snapshotPath = path.join(migrationsDir, SNAPSHOT_FILE);
33
+ fs.writeFileSync(snapshotPath, JSON.stringify(snapshot, null, 2));
34
+ }
35
+ /**
36
+ * Generate a timestamp-based migration name
37
+ */
38
+ function generateMigrationName(suffix) {
39
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[-:T]/g, "").slice(0, 14);
40
+ return suffix ? `${timestamp}_${suffix}` : timestamp;
41
+ }
42
+ /**
43
+ * Generate a migration from schema changes
44
+ *
45
+ * This compares the current schema to the stored snapshot and generates
46
+ * the necessary SQL statements to migrate the database.
47
+ *
48
+ * @example
49
+ * ```ts
50
+ * import { users, posts } from './schema';
51
+ *
52
+ * const result = await generateMigration({
53
+ * migrationsDir: './migrations',
54
+ * schema: { users, posts },
55
+ * });
56
+ *
57
+ * if (result.hasChanges) {
58
+ * console.log('Migration generated:', result.migrationName);
59
+ * }
60
+ * ```
61
+ */
62
+ async function generateMigration(options) {
63
+ const { migrationsDir, schema, migrationName, write = true } = options;
64
+ const previousSnapshot = loadSnapshot(migrationsDir);
65
+ const newSnapshot = await generateSnapshotFromSchema(schema);
66
+ newSnapshot.id = generateSnapshotId();
67
+ newSnapshot.prevId = previousSnapshot.id;
68
+ if (snapshotsEqual(previousSnapshot, newSnapshot)) return {
69
+ hasChanges: false,
70
+ statements: [],
71
+ migrationName: null,
72
+ snapshot: newSnapshot,
73
+ previousSnapshot
74
+ };
75
+ const statements = await generateMigrationStatements(previousSnapshot, newSnapshot);
76
+ const name = migrationName ?? generateMigrationName("auto");
77
+ if (write && statements.length > 0) {
78
+ fs.mkdirSync(migrationsDir, { recursive: true });
79
+ const sqlPath = path.join(migrationsDir, `${name}.sql`);
80
+ const sqlContent = statements.map((s) => s.endsWith(";") ? s : `${s};`).join("\n\n");
81
+ fs.writeFileSync(sqlPath, sqlContent);
82
+ saveSnapshot(migrationsDir, newSnapshot);
83
+ debugMigrations("Generated migration: %s", name);
84
+ debugMigrations("Statements: %d", statements.length);
85
+ }
86
+ return {
87
+ hasChanges: true,
88
+ statements,
89
+ migrationName: name,
90
+ snapshot: newSnapshot,
91
+ previousSnapshot
92
+ };
93
+ }
94
+ /**
95
+ * Breakpoint marker in SQL files
96
+ * Use: --> breakpoint
97
+ */
98
+ const BREAKPOINT_MARKER = /^-->\s*breakpoint\s*$/im;
99
+ /**
100
+ * Parse SQL content into chunks (split by breakpoints) and statements
101
+ *
102
+ * @param content - Raw SQL file content
103
+ * @returns Array of chunks, where each chunk is an array of SQL statements
104
+ */
105
+ function parseSqlMigration(content) {
106
+ return content.split(BREAKPOINT_MARKER).map((chunk) => {
107
+ return chunk.split("\n").filter((line) => !line.trim().startsWith("--")).join("\n").split(/;(?:\s*\n|\s*$)/).map((s) => s.trim()).filter((s) => s.length > 0);
108
+ }).filter((chunk) => chunk.length > 0);
109
+ }
110
+ /**
111
+ * Load all migration SQL files from a directory
112
+ * Returns migrations sorted by name (timestamp order) with breakpoint parsing
113
+ */
114
+ function loadMigrationFiles(migrationsDir) {
115
+ const migrations = /* @__PURE__ */ new Map();
116
+ if (!fs.existsSync(migrationsDir)) return migrations;
117
+ const files = fs.readdirSync(migrationsDir).filter((f) => f.endsWith(".sql")).sort();
118
+ for (const file of files) {
119
+ const name = file.replace(".sql", "");
120
+ const chunks = parseSqlMigration(fs.readFileSync(path.join(migrationsDir, file), "utf-8"));
121
+ if (chunks.length > 0) migrations.set(name, chunks);
122
+ }
123
+ return migrations;
124
+ }
125
+ /**
126
+ * Load a schema module using dynamic import
127
+ * Works with both ESM and CJS modules
128
+ */
129
+ async function loadSchemaModule(schemaPath, tableNames) {
130
+ const fileUrl = pathToFileURL(schemaPath).href;
131
+ try {
132
+ const module = await import(fileUrl);
133
+ const schema = {};
134
+ for (const name of tableNames) if (module[name]) schema[name] = module[name];
135
+ else if (module.default?.[name]) schema[name] = module.default[name];
136
+ return schema;
137
+ } catch (error) {
138
+ throw new Error(`Failed to load schema from ${schemaPath}: ${error}`);
139
+ }
140
+ }
141
+ /**
142
+ * Build schema module with esbuild and return the exports
143
+ * This is useful when the schema is TypeScript and needs transpilation
144
+ */
145
+ async function buildAndLoadSchema(schemaPath, tableNames) {
146
+ const result = await (await import("esbuild")).build({
147
+ entryPoints: [schemaPath],
148
+ bundle: true,
149
+ write: false,
150
+ format: "esm",
151
+ platform: "node",
152
+ packages: "external",
153
+ target: "node18"
154
+ });
155
+ if (result.outputFiles?.length !== 1) throw new Error(`Unexpected esbuild output for ${schemaPath}`);
156
+ const tempDir = path.dirname(schemaPath);
157
+ const tempFile = path.join(tempDir, `_schema_temp_${Date.now()}.mjs`);
158
+ try {
159
+ fs.writeFileSync(tempFile, result.outputFiles[0].text);
160
+ const module = await import(pathToFileURL(tempFile).href);
161
+ const schema = {};
162
+ for (const name of tableNames) if (module[name]) schema[name] = module[name];
163
+ else if (module.default?.[name]) schema[name] = module.default[name];
164
+ return schema;
165
+ } finally {
166
+ try {
167
+ fs.unlinkSync(tempFile);
168
+ } catch {}
169
+ }
170
+ }
171
+ /**
172
+ * Generate SQL to create all tables from scratch
173
+ * Useful for initial setup or testing
174
+ */
175
+ async function generateCreateTableSQL(schema) {
176
+ return generateMigrationStatements(createEmptySnapshot(), await generateSnapshotFromSchema(schema));
177
+ }
178
+
179
+ //#endregion
180
+ export { loadMigrationFiles as a, parseSqlMigration as c, generateMigrationName as i, saveSnapshot as l, generateCreateTableSQL as n, loadSchemaModule as o, generateMigration as r, loadSnapshot as s, buildAndLoadSchema as t };