durable-db 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  import { t as DatabaseSource } from "../discovery-gHeLq8jk.js";
2
- import "../index-rlnVnzJJ.js";
2
+ import "../index-BQ1hHyrq.js";
3
3
  import { Plugin } from "vite";
4
4
  import "@babel/types";
5
5
  //#region src/vite/modules/wrangler.d.ts
@@ -1,7 +1,7 @@
1
1
  import { i as init_debug, r as debugVite } from "../debug-Cz8KzMft.js";
2
2
  import { _ as saveDevState, d as init_state, l as getDevPaths, m as removeDevServerLock, p as loadDevState, s as getDatabaseEpochs, y as writeDevServerLock } from "../state-DGYycIoJ.js";
3
3
  import { loadMigrationFiles } from "../migrations/generator.js";
4
- import { a as discoverActionFiles, i as databaseSources, n as parseDatabaseFile, o as discoverDatabaseFiles, r as toPascalCase, s as readFile, t as BABEL_PARSER_PLUGINS } from "../parser-DyepmXzE.js";
4
+ import { a as databaseSources, c as readFile, i as toPascalCase, n as declaresSchema, o as discoverActionFiles, r as parseDatabaseFile, s as discoverDatabaseFiles, t as BABEL_PARSER_PLUGINS } from "../parser-mUnAtllk.js";
5
5
  import * as fs from "node:fs";
6
6
  import path, * as path$1 from "node:path";
7
7
  import { parse } from "@babel/parser";
@@ -745,8 +745,12 @@ function schemaLocalName(db, tableName) {
745
745
  const safe = (s) => s.replace(/[^A-Za-z0-9_$]/g, "_");
746
746
  return `__schema_${safe(db.name)}_${safe(tableName)}`;
747
747
  }
748
+ /** The schema as one object, when the schema module exports it whole (`schemaExport`). */
749
+ function schemaConstLocalName(db) {
750
+ return `__schema_${db.name.replace(/[^A-Za-z0-9_$]/g, "_")}`;
751
+ }
748
752
  function hasSchema(db) {
749
- return !!db.schemaImport && db.schemaTableNames.length > 0;
753
+ return !!db.schemaImport && declaresSchema(db);
750
754
  }
751
755
  /**
752
756
  * Import declaration bringing a database's schema tables into the generated
@@ -759,13 +763,26 @@ function hasSchema(db) {
759
763
  */
760
764
  function buildSchemaImport(db) {
761
765
  const source = db.schemaImport.startsWith(".") ? path.resolve(path.dirname(db.filePath), db.schemaImport) : db.schemaImport;
766
+ if (db.schemaExport) return createNamedImport([{
767
+ imported: db.schemaExport,
768
+ local: schemaConstLocalName(db)
769
+ }], source);
762
770
  return createNamedImport(db.schemaTableNames.map((tableName) => ({
763
771
  imported: tableName,
764
772
  local: schemaLocalName(db, tableName)
765
773
  })), source);
766
774
  }
775
+ /**
776
+ * The schema in the generated module: the const the schema module exports —
777
+ * the very object the app's own code holds —, or the listed tables under
778
+ * their names.
779
+ */
780
+ function buildSchemaExpression(db) {
781
+ if (db.schemaExport) return t.identifier(schemaConstLocalName(db));
782
+ return t.objectExpression(db.schemaTableNames.map((tableName) => t.objectProperty(t.identifier(tableName), t.identifier(schemaLocalName(db, tableName)))));
783
+ }
767
784
  function buildSchemaProperty(db) {
768
- return t.classProperty(t.identifier("schema"), t.objectExpression(db.schemaTableNames.map((tableName) => t.objectProperty(t.identifier(tableName), t.identifier(schemaLocalName(db, tableName))))));
785
+ return t.classProperty(t.identifier("schema"), buildSchemaExpression(db));
769
786
  }
770
787
  function buildDbTransportsObject(databases) {
771
788
  const properties = databases.map((db) => t.objectProperty(t.stringLiteral(db.name), t.stringLiteral(db.transport)));
@@ -822,6 +839,26 @@ function generateDurableObjectsModule(databases, registryImport, isDev = false,
822
839
  return generateCode(t.file(program));
823
840
  }
824
841
  /**
842
+ * `virtual:durable-db/__databases`: what the plugin discovered, for a library
843
+ * that needs to know which database a table belongs to —
844
+ *
845
+ * export const databases = [{ name, bindingName, className, instance, schema: { <table>: <the table> } }];
846
+ *
847
+ * The tables are imported from the schema module, as the Durable Object
848
+ * classes import them: the same objects the app's own code holds.
849
+ */
850
+ function generateDatabasesModule(databases) {
851
+ const entries = databases.map((db) => t.objectExpression([
852
+ t.objectProperty(t.identifier("name"), t.stringLiteral(db.name)),
853
+ t.objectProperty(t.identifier("bindingName"), t.stringLiteral(db.bindingName)),
854
+ t.objectProperty(t.identifier("className"), t.stringLiteral(db.className)),
855
+ t.objectProperty(t.identifier("instance"), t.stringLiteral(db.instance)),
856
+ t.objectProperty(t.identifier("schema"), hasSchema(db) ? buildSchemaExpression(db) : t.objectExpression([]))
857
+ ]));
858
+ const program = t.program([...databases.filter(hasSchema).map(buildSchemaImport), t.exportNamedDeclaration(t.variableDeclaration("const", [t.variableDeclarator(t.identifier("databases"), t.arrayExpression(entries))]))]);
859
+ return generateCode(t.file(program));
860
+ }
861
+ /**
825
862
  * `export class <Old>DatabaseDO extends RemovedDatabaseDurableObject { … }`:
826
863
  * the class of a removed database, kept so the worker still exports every
827
864
  * class its migrations declare — its storage untouched, every call refused.
@@ -1142,7 +1179,12 @@ function applyActionTransforms(body, ctx) {
1142
1179
  replaced.push(t.expressionStatement(t.callExpression(t.identifier("registerAction"), [
1143
1180
  t.stringLiteral(dbName),
1144
1181
  t.stringLiteral(exportName),
1145
- t.objectExpression([t.objectProperty(t.identifier("validator"), t.arrowFunctionExpression([t.identifier("args")], t.callExpression(validatorId, [t.identifier("args")]))), t.objectProperty(t.identifier("handler"), handlerId)])
1182
+ t.objectExpression([
1183
+ t.objectProperty(t.identifier("validator"), t.arrowFunctionExpression([t.identifier("args")], t.callExpression(validatorId, [t.identifier("args")]))),
1184
+ t.objectProperty(t.identifier("handler"), handlerId),
1185
+ t.objectProperty(t.identifier("args"), validatorId),
1186
+ t.objectProperty(t.identifier("stub"), t.identifier(exportName))
1187
+ ])
1146
1188
  ])));
1147
1189
  const funcDecl = t.functionDeclaration(t.identifier(exportName), [t.identifier("args")], t.blockStatement(buildStubBodyStatements({
1148
1190
  action,
@@ -1329,6 +1371,9 @@ const DURABLE_OBJECTS_ID = "durable-db/__durableObjects";
1329
1371
  const VIRTUAL_DO_MODULE_ID = "\0virtual:durable-db/__durableObjects.js";
1330
1372
  const DEV_EPOCH_ID = "durable-db/__devEpoch";
1331
1373
  const VIRTUAL_DEV_EPOCH_MODULE_ID = "\0virtual:durable-db/__devEpoch.js";
1374
+ /** The discovered databases, for whoever imports it (nothing of durable-db's does). */
1375
+ const DATABASES_ID = "durable-db/__databases";
1376
+ const VIRTUAL_DATABASES_MODULE_ID = "\0virtual:durable-db/__databases.js";
1332
1377
  /** Old org-prefixed spelling, still resolved for compatibility. */
1333
1378
  const LEGACY_ID_PREFIX = "eagerpatch/";
1334
1379
  /** Match a virtual id in all accepted spellings (`virtual:` optional, legacy prefix). */
@@ -1512,6 +1557,7 @@ var PluginState = class {
1512
1557
  }
1513
1558
  invalidateDOModule() {
1514
1559
  this.invalidateVirtualModule(VIRTUAL_DO_MODULE_ID);
1560
+ this.invalidateVirtualModule(VIRTUAL_DATABASES_MODULE_ID);
1515
1561
  }
1516
1562
  invalidateDevEpochModule() {
1517
1563
  this.invalidateVirtualModule(VIRTUAL_DEV_EPOCH_MODULE_ID);
@@ -1640,6 +1686,7 @@ function durableDb(options = {}) {
1640
1686
  resolveId(id) {
1641
1687
  if (matchesVirtualId(id, DURABLE_OBJECTS_ID)) return VIRTUAL_DO_MODULE_ID;
1642
1688
  if (matchesVirtualId(id, DEV_EPOCH_ID)) return VIRTUAL_DEV_EPOCH_MODULE_ID;
1689
+ if (matchesVirtualId(id, DATABASES_ID)) return VIRTUAL_DATABASES_MODULE_ID;
1643
1690
  return null;
1644
1691
  },
1645
1692
  async load(id) {
@@ -1658,6 +1705,10 @@ function durableDb(options = {}) {
1658
1705
  }
1659
1706
  return { code: generateDevEpochModule(epoch, databaseEpochs) };
1660
1707
  }
1708
+ if (id === VIRTUAL_DATABASES_MODULE_ID) {
1709
+ await state.initialize();
1710
+ return { code: generateDatabasesModule(Array.from(state.databases.values())) };
1711
+ }
1661
1712
  if (id !== VIRTUAL_DO_MODULE_ID) return null;
1662
1713
  await state.initialize();
1663
1714
  const isDev = state.config.command === "serve";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "durable-db",
3
- "version": "0.8.0",
3
+ "version": "0.10.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/eagerpatch/durable-db.git"
package/virtual.d.ts CHANGED
@@ -13,5 +13,17 @@ declare module "virtual:durable-db/__devEpoch" {
13
13
  export function applyDevEpoch(key: string, dbName?: string): string;
14
14
  }
15
15
 
16
+ // The databases the plugin discovered, each with its tables (the schema
17
+ // module's own objects) — for a library that maps a table to its database.
18
+ declare module "virtual:durable-db/__databases" {
19
+ export const databases: ReadonlyArray<{
20
+ name: string;
21
+ bindingName: string;
22
+ className: string;
23
+ instance: 'per-tenant' | 'global';
24
+ schema: Record<string, unknown>;
25
+ }>;
26
+ }
27
+
16
28
  /** @deprecated Use "virtual:durable-db/__durableObjects" instead. */
17
29
  declare module "virtual:eagerpatch/durable-db/__durableObjects";
@@ -1,110 +0,0 @@
1
- import { r as type } from "./type-CUgZsZp3.js";
2
- import { t as actionArgsType } from "./actionArgs-DP2tQrlf.js";
3
- //#region src/db/defineDatabase.ts
4
- /**
5
- * Non-enumerable property the source `action()` stashes on the function it
6
- * returns, carrying the original `{ args, handler }` config plus the compiled
7
- * arktype validator. The production Vite transform replaces `action()`
8
- * call-sites entirely, so this only ever exists in the UNTRANSFORMED world —
9
- * i.e. tests. The `durable-db/testing` harness reads it to run a handler
10
- * against a real in-memory database. See src/testing/index.ts.
11
- */
12
- const ACTION_TEST_META = Symbol.for("durable-db.actionTestMeta");
13
- /**
14
- * Where the live test databases are listed, newest last. On `globalThis`, not
15
- * module state: a test run can load `durable-db` (the app's actions) and
16
- * `durable-db/testing` as separate module copies.
17
- */
18
- const LIVE_TEST_DATABASES = Symbol.for("durable-db.liveTestDatabases");
19
- /** The live test databases (created on first use). */
20
- function liveTestDatabases() {
21
- const store = globalThis;
22
- return store[LIVE_TEST_DATABASES] ??= [];
23
- }
24
- /** The newest live test database holding every table of `schema`, if any. */
25
- function testDatabaseFor(schema) {
26
- const tables = Object.values(schema);
27
- if (tables.length === 0) return void 0;
28
- const live = globalThis[LIVE_TEST_DATABASES];
29
- if (!live) return void 0;
30
- for (let i = live.length - 1; i >= 0; i--) if (tables.every((table) => live[i].tables.has(table))) return live[i];
31
- }
32
- /** `createTestDatabase({ schema: { a, b } })` for this database, for messages. */
33
- function testDatabaseHint(schema) {
34
- const names = Object.keys(schema);
35
- return `createTestDatabase({ schema: { ${names.length > 0 ? names.join(", ") : "…"} } })`;
36
- }
37
- /**
38
- * Define a database with its schema and migrations.
39
- *
40
- * This function is transformed at build time by the durable-db Vite plugin.
41
- * At runtime, the actions returned will be RPC stubs that call into the
42
- * generated Durable Object.
43
- *
44
- * Outside the build — code under test calling an action directly — an action
45
- * runs against the test database `createTestDatabase()` created for its
46
- * database's tables (the newest one, when there are several); without one it
47
- * throws.
48
- *
49
- * @example
50
- * ```ts
51
- * import { defineDatabase } from 'durable-db';
52
- * import { users, posts } from './schema';
53
- *
54
- * export const { action } = defineDatabase({
55
- * schema: { users, posts },
56
- * });
57
- *
58
- * export const createUser = action({
59
- * args: { name: 'string', email: 'string.email' },
60
- * handler: async (db, args) => {
61
- * return db.insertInto('users').values({
62
- * id: crypto.randomUUID(),
63
- * name: args.name,
64
- * email: args.email
65
- * }).returningAll().executeTakeFirst();
66
- * },
67
- * });
68
- * ```
69
- */
70
- function defineDatabase(config) {
71
- const schema = config?.schema ?? {};
72
- const action = (actionConfig) => {
73
- const validator = actionArgsType(actionConfig.args);
74
- const argsDefinition = actionConfig.args;
75
- const argKeys = argsDefinition !== null && typeof argsDefinition === "object" ? Object.keys(argsDefinition) : null;
76
- const argsHint = argKeys ? ` (args: ${argKeys.length > 0 ? `{ ${argKeys.join(", ")} }` : "{}"})` : "";
77
- const actionFn = async (args) => {
78
- const testDatabase = testDatabaseFor(schema);
79
- if (testDatabase) return await testDatabase.run(actionFn, args);
80
- const result = validator(args);
81
- if (result instanceof type.errors) throw new Error(`Invalid args for action${argsHint}: ${result.summary}`);
82
- throw new Error(`Action${argsHint} called without transformation: action() call sites are transformed by the build; in tests, create the database with ${testDatabaseHint(schema)} and call the action, or use db.run(action, args).`);
83
- };
84
- Object.defineProperty(actionFn, ACTION_TEST_META, {
85
- value: {
86
- args: actionConfig.args,
87
- handler: actionConfig.handler,
88
- validator,
89
- schema
90
- },
91
- enumerable: false,
92
- configurable: true
93
- });
94
- return actionFn;
95
- };
96
- const destroyDatabase = async () => {
97
- const testDatabase = testDatabaseFor(schema);
98
- if (testDatabase) {
99
- testDatabase.clear();
100
- return;
101
- }
102
- throw new Error(`destroyDatabase() called without transformation: it is transformed by the build; in tests, create the database with ${testDatabaseHint(schema)} first.`);
103
- };
104
- return {
105
- action,
106
- destroyDatabase
107
- };
108
- }
109
- //#endregion
110
- export { defineDatabase as n, liveTestDatabases as r, ACTION_TEST_META as t };
@@ -1,200 +0,0 @@
1
- import "./index-bUUlOWfP.js";
2
- import { t as Outbox } from "./outbox-D3Q9n7Rt.js";
3
- import { type } from "arktype";
4
- import { SQLiteTableWithColumns } from "drizzle-orm/sqlite-core";
5
- import { Kysely } from "kysely";
6
- import { Kyselify } from "drizzle-orm/kysely";
7
- //#region src/db/types.d.ts
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
- * Messages for something outside the Durable Object — a queue, an email, a
55
- * webhook — delivered after the action succeeds (`durableDb({ outbox })`
56
- * names where): `ctx.outbox.push(message)`. Written with the action's
57
- * writes, at least once; a handler that throws records none.
58
- */
59
- outbox: Outbox;
60
- }
61
- /**
62
- * Configuration for an action
63
- *
64
- * `Def` is "the ArkType definition" – whatever you'd normally pass to `type(...)`:
65
- * { name: "string", email: "string.email" }
66
- * unions, tuples, ranges, etc. all work.
67
- */
68
- interface ActionConfig<Def, TResult, TSchema extends Record<string, SQLiteTableWithColumns<any>>, TEnv = unknown> {
69
- /**
70
- * ArkType definition for args.
71
- * Typed as `arkType.validate<Def>` so you get the SAME DSL autocomplete
72
- * as when you do `type(Def)` directly.
73
- */
74
- args: ArkDef<Def>;
75
- /**
76
- * The action handler
77
- */
78
- handler: (db: Kysely<DrizzleToKysely<TSchema>>, args: InferArgs<Def>, ctx: ActionContext<TEnv>) => Promise<TResult>;
79
- }
80
- /**
81
- * An action function that can be called from routes or other actions
82
- */
83
- type Action<TArgs, TResult> = (args: TArgs) => Promise<TResult>;
84
- /**
85
- * Return type of defineDatabase
86
- */
87
- interface DatabaseDefinition<TSchema extends Record<string, SQLiteTableWithColumns<any>>> {
88
- /**
89
- * Define an action that runs within the database context
90
- *
91
- * NOTE: the `const Def` *here* is crucial – it matches ArkType's own
92
- * `<const def>(def: type.validate<def>)` pattern and is what makes
93
- * `"string.email"` etc. behave properly.
94
- */
95
- action: <const Def, TResult, TEnv = unknown>(config: ActionConfig<Def, TResult, TSchema, TEnv>) => Action<InferArgs<Def>, TResult>;
96
- /**
97
- * Destroy the database instance, clearing all data via `ctx.storage.deleteAll()`.
98
- * The next action call will re-run migrations and start fresh.
99
- *
100
- * For per-tenant databases, targets the current tenant (via `getTenantId()`).
101
- * For global databases, targets the single shared instance.
102
- */
103
- destroyDatabase: () => Promise<void>;
104
- }
105
- /**
106
- * Information about a parsed database file
107
- */
108
- interface DatabaseInfo {
109
- /** File path to the database definition file */
110
- filePath: string;
111
- /** Database name derived from filename */
112
- name: string;
113
- /** Class name for the Durable Object */
114
- className: string;
115
- /** Binding name for wrangler config */
116
- bindingName: string;
117
- /** Instance strategy */
118
- instance: 'per-tenant' | 'global';
119
- /** Path to migrations directory */
120
- migrationsDir: string;
121
- /** Schema import source (relative path) */
122
- schemaImport: string | null;
123
- /** Names of schema tables */
124
- schemaTableNames: string[];
125
- /** Whether the DO should expose a browsable SQL endpoint */
126
- browsable: boolean | 'development';
127
- /** Transport for action stubs */
128
- transport: 'rpc' | 'websocket';
129
- /** Loaded migrations - Map of name -> chunks (each chunk is array of SQL statements) */
130
- migrations?: Map<string, string[][]>;
131
- }
132
- /**
133
- * Information about a parsed action
134
- */
135
- interface ActionInfo {
136
- /** Export name of the action */
137
- exportName: string;
138
- /** The args schema (as source code string for codegen) */
139
- argsSchemaSource: string;
140
- /** The handler function (as source code string for codegen) */
141
- handlerSource: string;
142
- /** The database this action belongs to */
143
- databaseName: string;
144
- /** File where the action is defined */
145
- sourceFile: string;
146
- }
147
- /**
148
- * Result of parsing a database file
149
- */
150
- interface ParsedDatabaseFile {
151
- /** Absolute file path */
152
- filePath: string;
153
- /** Database configuration if this file has defineDatabase */
154
- database: DatabaseInfo | null;
155
- /** Actions defined in this file */
156
- actions: ActionInfo[];
157
- /** Local imports (for dependency resolution) */
158
- localImports: Map<string, {
159
- source: string;
160
- imported: string;
161
- }>;
162
- }
163
- //#endregion
164
- //#region src/db/defineDatabase.d.ts
165
- /**
166
- * Define a database with its schema and migrations.
167
- *
168
- * This function is transformed at build time by the durable-db Vite plugin.
169
- * At runtime, the actions returned will be RPC stubs that call into the
170
- * generated Durable Object.
171
- *
172
- * Outside the build — code under test calling an action directly — an action
173
- * runs against the test database `createTestDatabase()` created for its
174
- * database's tables (the newest one, when there are several); without one it
175
- * throws.
176
- *
177
- * @example
178
- * ```ts
179
- * import { defineDatabase } from 'durable-db';
180
- * import { users, posts } from './schema';
181
- *
182
- * export const { action } = defineDatabase({
183
- * schema: { users, posts },
184
- * });
185
- *
186
- * export const createUser = action({
187
- * args: { name: 'string', email: 'string.email' },
188
- * handler: async (db, args) => {
189
- * return db.insertInto('users').values({
190
- * id: crypto.randomUUID(),
191
- * name: args.name,
192
- * email: args.email
193
- * }).returningAll().executeTakeFirst();
194
- * },
195
- * });
196
- * ```
197
- */
198
- declare function defineDatabase<TSchema extends Record<string, SQLiteTableWithColumns<any>>>(config: DatabaseConfig<TSchema>): DatabaseDefinition<TSchema>;
199
- //#endregion
200
- 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 };