durable-db 0.8.0 → 0.9.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.
@@ -0,0 +1,377 @@
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 { AliasNode, AliasedExpression, Expression, Kysely, KyselyPlugin, Selectable } from "kysely";
6
+ import { Kyselify } from "drizzle-orm/kysely";
7
+ //#region src/db/relations.d.ts
8
+ type AnySchema = Record<string, SQLiteTableWithColumns<any>>;
9
+ type RefOf<Col> = Col extends {
10
+ _: {
11
+ references: infer C;
12
+ };
13
+ } ? C : never;
14
+ type TableNameOf<Col> = Col extends {
15
+ _: {
16
+ tableName: infer N;
17
+ };
18
+ } ? N : never;
19
+ type ColumnsOf<T> = T extends {
20
+ _: {
21
+ columns: infer C;
22
+ };
23
+ } ? C : never;
24
+ type NameOf<T> = T extends {
25
+ _: {
26
+ name: infer N;
27
+ };
28
+ } ? N : never;
29
+ type KeyOf<S, Name> = { [K in keyof S & string]: NameOf<S[K]> extends Name ? K : never; }[keyof S & string];
30
+ type TargetOf$1<S, Col> = [RefOf<Col>] extends [never] ? never : string extends TableNameOf<RefOf<Col>> ? never : KeyOf<S, TableNameOf<RefOf<Col>>>;
31
+ /** Every foreign key of a schema the types know: the table and column that hold it, the table it points at. */
32
+ type Edge<S> = { [TK in keyof S & string]: { [CK in keyof ColumnsOf<S[TK]> & string]: [TargetOf$1<S, ColumnsOf<S[TK]>[CK]>] extends [never] ? never : {
33
+ table: TK;
34
+ column: CK;
35
+ target: TargetOf$1<S, ColumnsOf<S[TK]>[CK]>;
36
+ nullable: ColumnsOf<S[TK]>[CK] extends {
37
+ _: {
38
+ notNull: true;
39
+ };
40
+ } ? false : true;
41
+ }; }[keyof ColumnsOf<S[TK]> & string]; }[keyof S & string];
42
+ type AnyEdge = {
43
+ table: string;
44
+ column: string;
45
+ target: string;
46
+ nullable: boolean;
47
+ };
48
+ type ForwardName<K extends string> = K extends `${infer P}Id` ? P extends '' ? K : P : K extends `${infer P}_id` ? P extends '' ? K : P : K;
49
+ type IsUnion<T, U = T> = [T] extends [never] ? false : T extends unknown ? ([U] extends [T] ? false : true) : never;
50
+ type InverseName<S, E extends AnyEdge> = IsUnion<Extract<Edge<S>, {
51
+ table: E['table'];
52
+ target: E['target'];
53
+ }>> extends true ? `${E['table']}As${Capitalize<ForwardName<E['column']>>}` : E['table'];
54
+ /** A relation as the types describe it. */
55
+ type RelationType = {
56
+ kind: 'one';
57
+ target: string;
58
+ nullable: boolean;
59
+ } | {
60
+ kind: 'many';
61
+ target: string;
62
+ };
63
+ type Forward<S, TK> = { [E in Extract<Edge<S>, {
64
+ table: TK;
65
+ }> as ForwardName<E['column']>]: {
66
+ kind: 'one';
67
+ target: E['target'];
68
+ nullable: E['nullable'];
69
+ }; };
70
+ type Inverse<S, TK> = { [E in Extract<Edge<S>, {
71
+ target: TK;
72
+ }> as InverseName<S, E>]: {
73
+ kind: 'many';
74
+ target: E['table'];
75
+ }; };
76
+ /**
77
+ * The relations of a schema, per table: what its foreign keys say, in both
78
+ * directions.
79
+ *
80
+ * ```ts
81
+ * type R = Relations<typeof schema>;
82
+ * // R['invoices']['customer'] → { kind: 'one'; target: 'customers'; nullable: false }
83
+ * // R['customers']['invoices'] → { kind: 'many'; target: 'invoices' }
84
+ * ```
85
+ */
86
+ type Relations<S> = { [TK in keyof S & string]: { [N in keyof (Forward<S, TK> & Inverse<S, TK>)]: (Forward<S, TK> & Inverse<S, TK>)[N]; }; };
87
+ /** A relation as the runtime knows it. Tables are schema keys, columns their properties. */
88
+ interface Relation {
89
+ kind: 'one' | 'many';
90
+ name: string;
91
+ /** The table that has the relation. */
92
+ table: string;
93
+ /** The table it leads to. */
94
+ target: string;
95
+ /** The column of `table` the relation is matched on: the foreign key of a `one`, the referenced column of a `many`. */
96
+ local: string;
97
+ /** The column of `target` it matches. */
98
+ foreign: string;
99
+ /** A `one` whose foreign key may be null. Always false for a `many`. */
100
+ nullable: boolean;
101
+ }
102
+ /** `relations[table][name]`. */
103
+ type RelationMap = Record<string, Record<string, Relation>>;
104
+ /**
105
+ * The relations a schema's foreign keys declare, per table. Read the first
106
+ * time it is asked for (a foreign key's target is a callback, so every table
107
+ * of the schema exists by then) and kept.
108
+ */
109
+ declare function relationsOf(schema: AnySchema): RelationMap;
110
+ /** One relation of a table, or an error that says what there is. */
111
+ declare function relationOf(schema: AnySchema, table: string, name: string): Relation;
112
+ //#endregion
113
+ //#region src/db/related.d.ts
114
+ type Simplify<T> = { [K in keyof T]: T[K]; } & {};
115
+ type Row<S extends AnySchema, TK> = TK extends keyof S ? Selectable<DrizzleToKysely<S>[TK]> : never;
116
+ type TargetOf<Rel> = Rel extends {
117
+ target: infer T;
118
+ } ? T : never;
119
+ /** What the relations in `with` add to a row: each under its name. */
120
+ type Nested<W> = W extends readonly RelatedExpression<string, string, unknown>[] ? { [E in W[number] as E['alias']]: E extends RelatedExpression<string, string, infer V> ? V : never; } : {};
121
+ /** A `one` answers its row (or null, when the foreign key may be null), a `many` a list. */
122
+ type Value<Rel, Item> = Rel extends {
123
+ kind: 'one';
124
+ nullable: false;
125
+ } ? Item : Rel extends {
126
+ kind: 'one';
127
+ } ? Item | null : Item[];
128
+ interface RelatedOptions<C extends string, W, K extends string = C> {
129
+ /** The columns of the related table to read. */
130
+ columns: readonly C[];
131
+ /** Relations of the related table, read with each row: `related('<that table>', …)`. */
132
+ with?: W;
133
+ /** A `many` only: the order of its rows, first key first. */
134
+ orderBy?: { [P in K]?: 'asc' | 'desc'; };
135
+ /** A `many` only: at most this many rows per parent. */
136
+ limit?: number;
137
+ }
138
+ /**
139
+ * `related(table, relation, columns)`: the rows `relation` leads to from each
140
+ * row of `table`, as a selection.
141
+ */
142
+ interface Related<S extends AnySchema> {
143
+ <TK extends keyof Relations<S> & string, R extends keyof Relations<S>[TK] & string, C extends keyof Row<S, TargetOf<Relations<S>[TK][R]>> & string>(table: TK, relation: R, columns: readonly C[]): RelatedExpression<TK, R, Value<Relations<S>[TK][R], Simplify<Pick<Row<S, TargetOf<Relations<S>[TK][R]>>, C>>>>;
144
+ <TK extends keyof Relations<S> & string, R extends keyof Relations<S>[TK] & string, C extends keyof Row<S, TargetOf<Relations<S>[TK][R]>> & string, W extends readonly RelatedExpression<TargetOf<Relations<S>[TK][R]> & string, string, unknown>[] = []>(table: TK, relation: R, options: RelatedOptions<C, W, keyof Row<S, TargetOf<Relations<S>[TK][R]>> & string>): RelatedExpression<TK, R, Value<Relations<S>[TK][R], Simplify<Pick<Row<S, TargetOf<Relations<S>[TK][R]>>, C> & Nested<W>>>>;
145
+ }
146
+ /** A relation to read, checked against the schema. Internal: what `related()` builds. */
147
+ interface RelatedSpec {
148
+ schema: AnySchema;
149
+ relation: Relation;
150
+ columns: string[];
151
+ with: RelatedSpec[];
152
+ orderBy: [column: string, direction: 'asc' | 'desc'][];
153
+ limit?: number;
154
+ }
155
+ /**
156
+ * A relation as a selection: what `related()` returns. `table` is the table
157
+ * it is a relation of (so `with` takes only the related table's own), `alias`
158
+ * the relation's name — the key it is answered under.
159
+ */
160
+ declare class RelatedExpression<TK extends string, A extends string, V> implements AliasedExpression<V, A> {
161
+ readonly table: TK;
162
+ readonly alias: A;
163
+ constructor(spec: RelatedSpec);
164
+ get expression(): Expression<V>;
165
+ toOperationNode(): AliasNode;
166
+ }
167
+ //#endregion
168
+ //#region src/db/types.d.ts
169
+ /**
170
+ * Base type for ArkType schema definitions.
171
+ * This represents any valid arktype definition object.
172
+ */
173
+ type ArgsSchema = Record<string, unknown>;
174
+ /**
175
+ * Configuration for defineDatabase
176
+ */
177
+ interface DatabaseConfig<TSchema extends Record<string, SQLiteTableWithColumns<any>>> {
178
+ /** Drizzle schema tables */
179
+ schema: TSchema;
180
+ /** Instance strategy - 'per-tenant' (default) or 'global' */
181
+ instance?: 'per-tenant' | 'global';
182
+ /** Enable Outerbase Studio browsable SQL endpoint on this DO.
183
+ * - true: always enabled
184
+ * - false: always disabled (default)
185
+ * - 'development': enabled only in dev mode */
186
+ browsable?: boolean | 'development';
187
+ /** Transport for action stubs: 'rpc' (default) or 'websocket'.
188
+ * WebSocket uses Cloudflare's 20:1 message billing ratio for cheaper high-volume calls. */
189
+ transport?: 'rpc' | 'websocket';
190
+ }
191
+ /**
192
+ * Convert a Drizzle schema to Kysely database types using drizzle-kysely
193
+ */
194
+ type DrizzleToKysely<TSchema extends Record<string, SQLiteTableWithColumns<any>>> = { [K in keyof TSchema]: TSchema[K] extends SQLiteTableWithColumns<any> ? Kyselify<TSchema[K]> : never; };
195
+ /**
196
+ * ArkType helpers – mirror Ark's own API:
197
+ * - arkType.validate<Def> → definition shape with DSL validation/autocomplete
198
+ * - arkType.infer<Def> → inferred output type
199
+ */
200
+ type ArkDef<Def> = type.validate<Def>;
201
+ type InferArgs<Def> = type.infer<Def>;
202
+ /**
203
+ * Context passed to action handlers
204
+ */
205
+ interface ActionContext<TEnv = unknown> {
206
+ /** Environment bindings (DO bindings, KV, etc.) */
207
+ env: TEnv;
208
+ /**
209
+ * The instance key used to address this Durable Object.
210
+ * For per-tenant databases, this is the tenant ID.
211
+ * For global databases, this is 'global'.
212
+ */
213
+ instanceKey: string;
214
+ /**
215
+ * Messages for something outside the Durable Object — a queue, an email, a
216
+ * webhook — delivered after the action succeeds (`durableDb({ outbox })`
217
+ * names where): `ctx.outbox.push(message)`. Written with the action's
218
+ * writes, at least once; a handler that throws records none.
219
+ */
220
+ outbox: Outbox;
221
+ }
222
+ /**
223
+ * Configuration for an action
224
+ *
225
+ * `Def` is "the ArkType definition" – whatever you'd normally pass to `type(...)`:
226
+ * { name: "string", email: "string.email" }
227
+ * unions, tuples, ranges, etc. all work.
228
+ */
229
+ interface ActionConfig<Def, TResult, TSchema extends Record<string, SQLiteTableWithColumns<any>>, TEnv = unknown> {
230
+ /**
231
+ * ArkType definition for args.
232
+ * Typed as `arkType.validate<Def>` so you get the SAME DSL autocomplete
233
+ * as when you do `type(Def)` directly.
234
+ */
235
+ args: ArkDef<Def>;
236
+ /**
237
+ * The action handler
238
+ */
239
+ handler: (db: Kysely<DrizzleToKysely<TSchema>>, args: InferArgs<Def>, ctx: ActionContext<TEnv>) => Promise<TResult>;
240
+ }
241
+ /**
242
+ * An action function that can be called from routes or other actions
243
+ */
244
+ type Action<TArgs, TResult> = (args: TArgs) => Promise<TResult>;
245
+ /**
246
+ * Return type of defineDatabase
247
+ */
248
+ interface DatabaseDefinition<TSchema extends Record<string, SQLiteTableWithColumns<any>>> {
249
+ /**
250
+ * Define an action that runs within the database context
251
+ *
252
+ * NOTE: the `const Def` *here* is crucial – it matches ArkType's own
253
+ * `<const def>(def: type.validate<def>)` pattern and is what makes
254
+ * `"string.email"` etc. behave properly.
255
+ */
256
+ action: <const Def, TResult, TEnv = unknown>(config: ActionConfig<Def, TResult, TSchema, TEnv>) => Action<InferArgs<Def>, TResult>;
257
+ /**
258
+ * A relation of a table as a selection: the rows a foreign key leads to,
259
+ * read in the query that reads the row.
260
+ *
261
+ * db.selectFrom('invoices')
262
+ * .select(['invoices.id', related('invoices', 'customer', ['id', 'name'])])
263
+ *
264
+ * A relation is a column with `.references(() => other.column)`, named in
265
+ * both directions (see `relations`).
266
+ */
267
+ related: Related<TSchema>;
268
+ /**
269
+ * The relations the schema's foreign keys declare, by table and name:
270
+ * `relations.invoices.customer` (one), `relations.customers.invoices` (many).
271
+ */
272
+ readonly relations: RelationMap;
273
+ /**
274
+ * Destroy the database instance, clearing all data via `ctx.storage.deleteAll()`.
275
+ * The next action call will re-run migrations and start fresh.
276
+ *
277
+ * For per-tenant databases, targets the current tenant (via `getTenantId()`).
278
+ * For global databases, targets the single shared instance.
279
+ */
280
+ destroyDatabase: () => Promise<void>;
281
+ }
282
+ /**
283
+ * Information about a parsed database file
284
+ */
285
+ interface DatabaseInfo {
286
+ /** File path to the database definition file */
287
+ filePath: string;
288
+ /** Database name derived from filename */
289
+ name: string;
290
+ /** Class name for the Durable Object */
291
+ className: string;
292
+ /** Binding name for wrangler config */
293
+ bindingName: string;
294
+ /** Instance strategy */
295
+ instance: 'per-tenant' | 'global';
296
+ /** Path to migrations directory */
297
+ migrationsDir: string;
298
+ /** Schema import source (relative path) */
299
+ schemaImport: string | null;
300
+ /** Names of schema tables */
301
+ schemaTableNames: string[];
302
+ /** Whether the DO should expose a browsable SQL endpoint */
303
+ browsable: boolean | 'development';
304
+ /** Transport for action stubs */
305
+ transport: 'rpc' | 'websocket';
306
+ /** Loaded migrations - Map of name -> chunks (each chunk is array of SQL statements) */
307
+ migrations?: Map<string, string[][]>;
308
+ }
309
+ /**
310
+ * Information about a parsed action
311
+ */
312
+ interface ActionInfo {
313
+ /** Export name of the action */
314
+ exportName: string;
315
+ /** The args schema (as source code string for codegen) */
316
+ argsSchemaSource: string;
317
+ /** The handler function (as source code string for codegen) */
318
+ handlerSource: string;
319
+ /** The database this action belongs to */
320
+ databaseName: string;
321
+ /** File where the action is defined */
322
+ sourceFile: string;
323
+ }
324
+ /**
325
+ * Result of parsing a database file
326
+ */
327
+ interface ParsedDatabaseFile {
328
+ /** Absolute file path */
329
+ filePath: string;
330
+ /** Database configuration if this file has defineDatabase */
331
+ database: DatabaseInfo | null;
332
+ /** Actions defined in this file */
333
+ actions: ActionInfo[];
334
+ /** Local imports (for dependency resolution) */
335
+ localImports: Map<string, {
336
+ source: string;
337
+ imported: string;
338
+ }>;
339
+ }
340
+ //#endregion
341
+ //#region src/db/defineDatabase.d.ts
342
+ /**
343
+ * Define a database with its schema and migrations.
344
+ *
345
+ * This function is transformed at build time by the durable-db Vite plugin.
346
+ * At runtime, the actions returned will be RPC stubs that call into the
347
+ * generated Durable Object.
348
+ *
349
+ * Outside the build — code under test calling an action directly — an action
350
+ * runs against the test database `createTestDatabase()` created for its
351
+ * database's tables (the newest one, when there are several); without one it
352
+ * throws.
353
+ *
354
+ * @example
355
+ * ```ts
356
+ * import { defineDatabase } from 'durable-db';
357
+ * import { users, posts } from './schema';
358
+ *
359
+ * export const { action } = defineDatabase({
360
+ * schema: { users, posts },
361
+ * });
362
+ *
363
+ * export const createUser = action({
364
+ * args: { name: 'string', email: 'string.email' },
365
+ * handler: async (db, args) => {
366
+ * return db.insertInto('users').values({
367
+ * id: crypto.randomUUID(),
368
+ * name: args.name,
369
+ * email: args.email
370
+ * }).returningAll().executeTakeFirst();
371
+ * },
372
+ * });
373
+ * ```
374
+ */
375
+ declare function defineDatabase<TSchema extends Record<string, SQLiteTableWithColumns<any>>>(config: DatabaseConfig<TSchema>): DatabaseDefinition<TSchema>;
376
+ //#endregion
377
+ export { RelationMap as _, ActionInfo as a, relationOf as b, DatabaseDefinition as c, InferArgs as d, ParsedDatabaseFile as f, Relation as g, RelatedOptions as h, ActionContext as i, DatabaseInfo as l, RelatedExpression as m, Action as n, ArgsSchema as o, Related as p, ActionConfig as r, DatabaseConfig as s, defineDatabase as t, DrizzleToKysely as u, RelationType as v, relationsOf as x, Relations as y };