viborm 0.1.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.
- package/README.md +529 -0
- package/dist/adapters.d.mts +2 -0
- package/dist/adapters.mjs +1 -0
- package/dist/bun-sql.d.mts +3 -0
- package/dist/bun-sql.mjs +2 -0
- package/dist/bun-sql.mjs.map +1 -0
- package/dist/bun-sqlite.d.mts +3 -0
- package/dist/bun-sqlite.mjs +2 -0
- package/dist/bun-sqlite.mjs.map +1 -0
- package/dist/cache/cloudflare-kv.d.mts +3 -0
- package/dist/cache/cloudflare-kv.mjs +2 -0
- package/dist/cache/cloudflare-kv.mjs.map +1 -0
- package/dist/cache/memory.d.mts +3 -0
- package/dist/cache/memory.mjs +2 -0
- package/dist/cache/memory.mjs.map +1 -0
- package/dist/cache.d.mts +4 -0
- package/dist/cache.mjs +1 -0
- package/dist/cli.d.mts +1 -0
- package/dist/cli.mjs +41 -0
- package/dist/cli.mjs.map +1 -0
- package/dist/client-CgdtiDGV.mjs +2 -0
- package/dist/client-CgdtiDGV.mjs.map +1 -0
- package/dist/client.d.mts +3 -0
- package/dist/client.mjs +1 -0
- package/dist/cloudflare-kv-DauXhtnT.d.mts +1110 -0
- package/dist/d1-http.d.mts +3 -0
- package/dist/d1-http.mjs +2 -0
- package/dist/d1-http.mjs.map +1 -0
- package/dist/d1.d.mts +3 -0
- package/dist/d1.mjs +2 -0
- package/dist/d1.mjs.map +1 -0
- package/dist/driver-B_vBzQ6A.mjs +2 -0
- package/dist/driver-B_vBzQ6A.mjs.map +1 -0
- package/dist/driver-Cj1EbciY.mjs +2 -0
- package/dist/driver-Cj1EbciY.mjs.map +1 -0
- package/dist/driver.d.mts +2 -0
- package/dist/driver.mjs +1 -0
- package/dist/errors-DvcqIdEo.mjs +2 -0
- package/dist/errors-DvcqIdEo.mjs.map +1 -0
- package/dist/helper-cDCDjRAD.d.mts +3020 -0
- package/dist/helpers-WNr9B-2U.mjs +2 -0
- package/dist/helpers-WNr9B-2U.mjs.map +1 -0
- package/dist/hydration-CFnwc7j6.mjs +2 -0
- package/dist/hydration-CFnwc7j6.mjs.map +1 -0
- package/dist/index-3sdVKfeG.d.mts +1447 -0
- package/dist/index-BGmpst1h.d.mts +2158 -0
- package/dist/index.d.mts +46 -0
- package/dist/index.mjs +2 -0
- package/dist/index.mjs.map +1 -0
- package/dist/instrumentation.d.mts +2 -0
- package/dist/instrumentation.mjs +1 -0
- package/dist/libsql.d.mts +3 -0
- package/dist/libsql.mjs +2 -0
- package/dist/libsql.mjs.map +1 -0
- package/dist/migrations.d.mts +1588 -0
- package/dist/migrations.mjs +11 -0
- package/dist/migrations.mjs.map +1 -0
- package/dist/mysql-adapter-0catKeCI.mjs +6 -0
- package/dist/mysql-adapter-0catKeCI.mjs.map +1 -0
- package/dist/mysql-utils-BPw9qhac.mjs +2 -0
- package/dist/mysql-utils-BPw9qhac.mjs.map +1 -0
- package/dist/mysql2.d.mts +3 -0
- package/dist/mysql2.mjs +2 -0
- package/dist/mysql2.mjs.map +1 -0
- package/dist/native-types-BwICkVjz.mjs +2 -0
- package/dist/native-types-BwICkVjz.mjs.map +1 -0
- package/dist/neon-http.d.mts +3 -0
- package/dist/neon-http.mjs +2 -0
- package/dist/neon-http.mjs.map +1 -0
- package/dist/pending-operation-CkzYTpi4.mjs +2 -0
- package/dist/pending-operation-CkzYTpi4.mjs.map +1 -0
- package/dist/pg.d.mts +3 -0
- package/dist/pg.mjs +2 -0
- package/dist/pg.mjs.map +1 -0
- package/dist/pglite.d.mts +3 -0
- package/dist/pglite.mjs +2 -0
- package/dist/pglite.mjs.map +1 -0
- package/dist/planetscale.d.mts +3 -0
- package/dist/planetscale.mjs +2 -0
- package/dist/planetscale.mjs.map +1 -0
- package/dist/postgres-adapter-Blzqj1bl.mjs +6 -0
- package/dist/postgres-adapter-Blzqj1bl.mjs.map +1 -0
- package/dist/postgres.d.mts +3 -0
- package/dist/postgres.mjs +2 -0
- package/dist/postgres.mjs.map +1 -0
- package/dist/push-qZreXYkb.mjs +252 -0
- package/dist/push-qZreXYkb.mjs.map +1 -0
- package/dist/result-parsing-FNQbuHvC.mjs +2 -0
- package/dist/result-parsing-FNQbuHvC.mjs.map +1 -0
- package/dist/schema-DeAJZocc.mjs +2 -0
- package/dist/schema-DeAJZocc.mjs.map +1 -0
- package/dist/schema.d.mts +293 -0
- package/dist/schema.mjs +2 -0
- package/dist/schema.mjs.map +1 -0
- package/dist/spans-CJt5UgbJ.mjs +2 -0
- package/dist/spans-CJt5UgbJ.mjs.map +1 -0
- package/dist/sqlite-adapter-5Em_-oGU.mjs +6 -0
- package/dist/sqlite-adapter-5Em_-oGU.mjs.map +1 -0
- package/dist/sqlite-utils-BW7elKTz.mjs +2 -0
- package/dist/sqlite-utils-BW7elKTz.mjs.map +1 -0
- package/dist/sqlite3.d.mts +3 -0
- package/dist/sqlite3.mjs +2 -0
- package/dist/sqlite3.mjs.map +1 -0
- package/dist/tracer-CGzIAsj8.mjs +2 -0
- package/dist/tracer-CGzIAsj8.mjs.map +1 -0
- package/dist/validation-RtU-wu4N.mjs +2 -0
- package/dist/validation-RtU-wu4N.mjs.map +1 -0
- package/dist/validation.d.mts +2 -0
- package/dist/validation.mjs +1 -0
- package/dist/validator-DpJsJcd7.mjs +3 -0
- package/dist/validator-DpJsJcd7.mjs.map +1 -0
- package/package.json +278 -0
- package/readme/README.md +69 -0
package/README.md
ADDED
|
@@ -0,0 +1,529 @@
|
|
|
1
|
+
# VibORM
|
|
2
|
+
|
|
3
|
+
Type-safe TypeScript ORM with **zero code generation**. Types are inferred from schema definitions at compile time—no `prisma generate` needed.
|
|
4
|
+
|
|
5
|
+
## Key Features
|
|
6
|
+
|
|
7
|
+
| Feature | Description |
|
|
8
|
+
|---------|-------------|
|
|
9
|
+
| **Zero Codegen** | Types flow from schema → query → result via TypeScript inference |
|
|
10
|
+
| **Standard Schema V1** | Interoperable with Zod, Valibot, ArkType for validation |
|
|
11
|
+
| **Prisma-like API** | Familiar `findMany`, `create`, `update` operations with `where`, `include`, `select` |
|
|
12
|
+
| **Multi-Database** | PostgreSQL, MySQL, SQLite from one codebase via adapter pattern |
|
|
13
|
+
| **Chainable Schema** | `s.string().nullable().unique()` with immutable state tracking |
|
|
14
|
+
|
|
15
|
+
```typescript
|
|
16
|
+
import { s } from "viborm";
|
|
17
|
+
import { createClient } from "viborm/drivers/pglite";
|
|
18
|
+
|
|
19
|
+
// Schema carries type information
|
|
20
|
+
const user = s.model({
|
|
21
|
+
id: s.string().id().ulid(),
|
|
22
|
+
email: s.string().unique(),
|
|
23
|
+
posts: s.oneToMany(() => post),
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
const post = s.model({
|
|
27
|
+
id: s.string().id().ulid(),
|
|
28
|
+
title: s.string(),
|
|
29
|
+
authorId: s.string(),
|
|
30
|
+
author: s.manyToOne(() => user).fields("authorId").references("id"),
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
// Fully typed queries - no codegen!
|
|
34
|
+
const orm = createClient({ schema: { user, post } });
|
|
35
|
+
|
|
36
|
+
const users = await orm.user.findMany({
|
|
37
|
+
where: { email: { contains: "@company.com" } }, // ← TypeScript knows email is string
|
|
38
|
+
include: { posts: true } // ← Result includes typed posts[]
|
|
39
|
+
});
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
---
|
|
43
|
+
|
|
44
|
+
## Quick Start (PGlite)
|
|
45
|
+
|
|
46
|
+
PGlite runs PostgreSQL in-process via WebAssembly—no Docker or external database needed. Perfect for development and testing.
|
|
47
|
+
|
|
48
|
+
### 1. Install
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
pnpm add viborm @electric-sql/pglite
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
### 2. Define Schema
|
|
55
|
+
|
|
56
|
+
```typescript
|
|
57
|
+
// schema.ts
|
|
58
|
+
import { s } from "viborm";
|
|
59
|
+
|
|
60
|
+
export const user = s.model({
|
|
61
|
+
id: s.string().id().ulid(),
|
|
62
|
+
name: s.string(),
|
|
63
|
+
email: s.string().unique(),
|
|
64
|
+
createdAt: s.dateTime().now(),
|
|
65
|
+
posts: s.oneToMany(() => post),
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
export const post = s.model({
|
|
69
|
+
id: s.string().id().ulid(),
|
|
70
|
+
title: s.string(),
|
|
71
|
+
content: s.string().nullable(),
|
|
72
|
+
authorId: s.string(),
|
|
73
|
+
author: s.manyToOne(() => user).fields("authorId").references("id"),
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
export const schema = { user, post };
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
### 3. Create Client & Push Schema
|
|
80
|
+
|
|
81
|
+
```typescript
|
|
82
|
+
// db.ts
|
|
83
|
+
import { createClient } from "viborm/drivers/pglite";
|
|
84
|
+
import { push } from "viborm/migrations";
|
|
85
|
+
import { schema } from "./schema";
|
|
86
|
+
|
|
87
|
+
export const orm = createClient({
|
|
88
|
+
schema,
|
|
89
|
+
dataDir: ".pglite", // Persists to filesystem (omit for in-memory)
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
// Push schema to database (creates tables)
|
|
93
|
+
await push(orm, schema);
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
### 4. Query
|
|
97
|
+
|
|
98
|
+
```typescript
|
|
99
|
+
// Create
|
|
100
|
+
const newUser = await orm.user.create({
|
|
101
|
+
data: { name: "Alice", email: "alice@example.com" }
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
// Read with relations
|
|
105
|
+
const usersWithPosts = await orm.user.findMany({
|
|
106
|
+
include: { posts: true }
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
// Filter
|
|
110
|
+
const alice = await orm.user.findFirst({
|
|
111
|
+
where: { email: { contains: "alice" } }
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
// Update
|
|
115
|
+
await orm.user.update({
|
|
116
|
+
where: { id: newUser.id },
|
|
117
|
+
data: { name: "Alice Smith" }
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
// Delete
|
|
121
|
+
await orm.user.delete({
|
|
122
|
+
where: { id: newUser.id }
|
|
123
|
+
});
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
---
|
|
127
|
+
|
|
128
|
+
## Transactions
|
|
129
|
+
|
|
130
|
+
VibORM supports transactions with two modes:
|
|
131
|
+
|
|
132
|
+
### Callback Mode (Dynamic)
|
|
133
|
+
|
|
134
|
+
```typescript
|
|
135
|
+
const result = await orm.$transaction(async (tx) => {
|
|
136
|
+
const user = await tx.user.create({
|
|
137
|
+
data: { name: "Alice", email: "alice@example.com" }
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
await tx.post.create({
|
|
141
|
+
data: { title: "First Post", authorId: user.id }
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
return user;
|
|
145
|
+
});
|
|
146
|
+
// If any operation fails, all changes are rolled back
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
### Batch Mode (Array)
|
|
150
|
+
|
|
151
|
+
```typescript
|
|
152
|
+
const [user, post] = await orm.$transaction([
|
|
153
|
+
orm.user.create({ data: { name: "Bob", email: "bob@example.com" } }),
|
|
154
|
+
orm.post.create({ data: { title: "Hello", authorId: "user-id" } })
|
|
155
|
+
]);
|
|
156
|
+
// All operations execute in a single transaction
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
---
|
|
160
|
+
|
|
161
|
+
## Caching
|
|
162
|
+
|
|
163
|
+
VibORM includes built-in query caching with TTL and stale-while-revalidate (SWR) support.
|
|
164
|
+
|
|
165
|
+
### Setup
|
|
166
|
+
|
|
167
|
+
```typescript
|
|
168
|
+
import { createClient } from "viborm/drivers/pglite";
|
|
169
|
+
import { MemoryCache } from "viborm/cache";
|
|
170
|
+
|
|
171
|
+
const orm = createClient({
|
|
172
|
+
schema,
|
|
173
|
+
cache: new MemoryCache(),
|
|
174
|
+
});
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
### Basic Caching
|
|
178
|
+
|
|
179
|
+
```typescript
|
|
180
|
+
// Cache for 5 minutes (default)
|
|
181
|
+
const users = await orm.$withCache().user.findMany();
|
|
182
|
+
|
|
183
|
+
// Custom TTL
|
|
184
|
+
const posts = await orm.$withCache({ ttl: "1 hour" }).post.findMany();
|
|
185
|
+
|
|
186
|
+
// TTL in milliseconds
|
|
187
|
+
const recent = await orm.$withCache({ ttl: 30000 }).user.findMany();
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
### Stale-While-Revalidate (SWR)
|
|
191
|
+
|
|
192
|
+
SWR returns stale data immediately while revalidating in the background:
|
|
193
|
+
|
|
194
|
+
```typescript
|
|
195
|
+
// Enable SWR with default 2x TTL stale window
|
|
196
|
+
const users = await orm.$withCache({ ttl: "5 minutes", swr: true }).user.findMany();
|
|
197
|
+
|
|
198
|
+
// Custom SWR window
|
|
199
|
+
const posts = await orm.$withCache({ ttl: "5 minutes", swr: "1 hour" }).post.findMany();
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
### Cache Invalidation
|
|
203
|
+
|
|
204
|
+
```typescript
|
|
205
|
+
// Auto-invalidate model cache after mutations
|
|
206
|
+
await orm.user.create({
|
|
207
|
+
data: { name: "Alice", email: "alice@example.com" },
|
|
208
|
+
cache: { autoInvalidate: true } // Invalidates all user:* cache keys
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
// Manual prefix invalidation with wildcard patterns
|
|
212
|
+
await orm.$invalidate("user:*", "post:findMany:*");
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
### Cache Drivers
|
|
216
|
+
|
|
217
|
+
| Driver | Use Case |
|
|
218
|
+
|--------|----------|
|
|
219
|
+
| `MemoryCache` | Development, single-instance deployments |
|
|
220
|
+
| `CloudflareKVCache` | Cloudflare Workers with KV |
|
|
221
|
+
|
|
222
|
+
---
|
|
223
|
+
|
|
224
|
+
## Instrumentation
|
|
225
|
+
|
|
226
|
+
VibORM supports OpenTelemetry tracing and structured logging.
|
|
227
|
+
|
|
228
|
+
### Setup
|
|
229
|
+
|
|
230
|
+
```typescript
|
|
231
|
+
import { createClient } from "viborm/drivers/pglite";
|
|
232
|
+
|
|
233
|
+
const orm = createClient({
|
|
234
|
+
schema,
|
|
235
|
+
instrumentation: {
|
|
236
|
+
tracing: {
|
|
237
|
+
enabled: true,
|
|
238
|
+
// Optional: customize tracer
|
|
239
|
+
},
|
|
240
|
+
logging: {
|
|
241
|
+
query: true, // Log SQL queries
|
|
242
|
+
cache: true, // Log cache hits/misses
|
|
243
|
+
warning: true, // Log warnings
|
|
244
|
+
error: true, // Log errors
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
});
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
### Serverless Support
|
|
251
|
+
|
|
252
|
+
For serverless environments, provide a `waitUntil` function to ensure background operations complete:
|
|
253
|
+
|
|
254
|
+
```typescript
|
|
255
|
+
// Cloudflare Workers
|
|
256
|
+
export default {
|
|
257
|
+
async fetch(request, env, ctx) {
|
|
258
|
+
const orm = createClient({
|
|
259
|
+
schema,
|
|
260
|
+
waitUntil: ctx.waitUntil.bind(ctx),
|
|
261
|
+
});
|
|
262
|
+
// ...
|
|
263
|
+
}
|
|
264
|
+
};
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
---
|
|
268
|
+
|
|
269
|
+
## Field Types
|
|
270
|
+
|
|
271
|
+
| Type | Description | Example |
|
|
272
|
+
|------|-------------|---------|
|
|
273
|
+
| `string()` | Text fields | `s.string().unique()` |
|
|
274
|
+
| `int()` | 32-bit integers | `s.int().default(0)` |
|
|
275
|
+
| `float()` | Floating-point | `s.float()` |
|
|
276
|
+
| `decimal()` | High-precision decimals | `s.decimal()` |
|
|
277
|
+
| `bigInt()` | 64-bit integers | `s.bigInt()` |
|
|
278
|
+
| `boolean()` | Boolean values | `s.boolean().default(false)` |
|
|
279
|
+
| `dateTime()` | Date and time | `s.dateTime().now()` |
|
|
280
|
+
| `date()` | Date only | `s.date()` |
|
|
281
|
+
| `time()` | Time only | `s.time()` |
|
|
282
|
+
| `json()` | JSON with schema validation | `s.json(zodSchema)` |
|
|
283
|
+
| `enum()` | Enumerated values | `s.enum(["ADMIN", "USER"])` |
|
|
284
|
+
| `blob()` | Binary data (Uint8Array) | `s.blob()` |
|
|
285
|
+
| `vector()` | Vector embeddings (pgvector) | `s.vector(1536)` |
|
|
286
|
+
| `point()` | PostGIS point type | `s.point()` |
|
|
287
|
+
|
|
288
|
+
### Auto-generation
|
|
289
|
+
|
|
290
|
+
```typescript
|
|
291
|
+
s.string().id().uuid() // UUID v4
|
|
292
|
+
s.string().id().ulid() // ULID
|
|
293
|
+
s.string().id().nanoid() // NanoID
|
|
294
|
+
s.string().id().cuid() // CUID
|
|
295
|
+
s.int().id().increment() // Auto-increment
|
|
296
|
+
s.dateTime().now() // Current timestamp on create
|
|
297
|
+
s.dateTime().updatedAt() // Update timestamp on every update
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
---
|
|
301
|
+
|
|
302
|
+
## Supported Drivers
|
|
303
|
+
|
|
304
|
+
### PostgreSQL
|
|
305
|
+
|
|
306
|
+
| Driver | Package | Use Case |
|
|
307
|
+
|--------|---------|----------|
|
|
308
|
+
| `pglite` | `@electric-sql/pglite` | Development, testing (WASM) |
|
|
309
|
+
| `pg` | `pg` | Node.js with node-postgres |
|
|
310
|
+
| `postgres` | `postgres` | Node.js with postgres.js |
|
|
311
|
+
| `neon-http` | `@neondatabase/serverless` | Neon serverless (HTTP) |
|
|
312
|
+
|
|
313
|
+
### MySQL
|
|
314
|
+
|
|
315
|
+
| Driver | Package | Use Case |
|
|
316
|
+
|--------|---------|----------|
|
|
317
|
+
| `mysql2` | `mysql2` | Node.js with mysql2 |
|
|
318
|
+
| `planetscale` | `@planetscale/database` | PlanetScale serverless |
|
|
319
|
+
|
|
320
|
+
### SQLite
|
|
321
|
+
|
|
322
|
+
| Driver | Package | Use Case |
|
|
323
|
+
|--------|---------|----------|
|
|
324
|
+
| `sqlite3` | `better-sqlite3` | Node.js (synchronous) |
|
|
325
|
+
| `libsql` | `@libsql/client` | Turso / LibSQL |
|
|
326
|
+
| `d1` | Cloudflare binding | Cloudflare D1 (Workers) |
|
|
327
|
+
| `d1-http` | Cloudflare API | Cloudflare D1 (HTTP) |
|
|
328
|
+
| `bun-sqlite` | Built-in | Bun runtime |
|
|
329
|
+
|
|
330
|
+
---
|
|
331
|
+
|
|
332
|
+
## Repository Structure
|
|
333
|
+
|
|
334
|
+
VibORM uses a **10-layer architecture**. Each layer has an `AGENTS.md` with detailed documentation.
|
|
335
|
+
|
|
336
|
+
```
|
|
337
|
+
src/
|
|
338
|
+
├── validation/ L1 Standard Schema V1 primitives (v.*)
|
|
339
|
+
│ Branded types, set-theory optimization
|
|
340
|
+
│
|
|
341
|
+
├── schema/ L2-L5 Schema definition
|
|
342
|
+
│ ├── fields/ Field types with State generic pattern
|
|
343
|
+
│ ├── model/ Model composition, query schemas
|
|
344
|
+
│ ├── relation/ Relation types (oneToMany, manyToOne, etc.)
|
|
345
|
+
│ └── validation/ Definition-time schema validation
|
|
346
|
+
│
|
|
347
|
+
├── query-engine/ L6 Database-agnostic query building
|
|
348
|
+
│ Decides WHAT to query, delegates HOW to adapters
|
|
349
|
+
│
|
|
350
|
+
├── adapters/ L7 Database-specific SQL generation
|
|
351
|
+
│ PostgreSQL, MySQL, SQLite dialect implementations
|
|
352
|
+
│
|
|
353
|
+
├── drivers/ L8 Connection management, query execution
|
|
354
|
+
│ 12 drivers: pglite, pg, postgres, neon-http, bun-sql,
|
|
355
|
+
│ mysql2, planetscale, sqlite3, libsql, d1, d1-http, bun-sqlite
|
|
356
|
+
│
|
|
357
|
+
├── client/ L9 Type inference, ORM interface
|
|
358
|
+
│ Recursive proxy pattern, result types
|
|
359
|
+
│
|
|
360
|
+
└── migrations/ L10 Schema diffing, push
|
|
361
|
+
```
|
|
362
|
+
|
|
363
|
+
### Key Architecture Rules
|
|
364
|
+
|
|
365
|
+
1. **Query Engine / Adapter Separation**: Query engine decides WHAT to query, adapter decides HOW to express it in SQL. Never hardcode dialect-specific syntax in query-engine.
|
|
366
|
+
|
|
367
|
+
2. **Natural Type Inference**: Never use type assertions (`as`). Types flow from schema → validation → client.
|
|
368
|
+
|
|
369
|
+
3. **Immutable State**: Every field modifier returns a NEW instance. `s.string().nullable()` returns a new field, doesn't mutate.
|
|
370
|
+
|
|
371
|
+
4. **Lazy Evaluation**: Schemas are built on first access (`??=` pattern) and cached.
|
|
372
|
+
|
|
373
|
+
---
|
|
374
|
+
|
|
375
|
+
## Development
|
|
376
|
+
|
|
377
|
+
### Prerequisites
|
|
378
|
+
|
|
379
|
+
```bash
|
|
380
|
+
pnpm install
|
|
381
|
+
```
|
|
382
|
+
|
|
383
|
+
### Testing (Vitest)
|
|
384
|
+
|
|
385
|
+
We use [Vitest](https://vitest.dev/) for testing. Tests run against PGlite by default—no external database needed.
|
|
386
|
+
|
|
387
|
+
```bash
|
|
388
|
+
pnpm test # Run all tests
|
|
389
|
+
pnpm test:watch # Watch mode
|
|
390
|
+
pnpm test:ui # ⭐ Interactive UI - great for exploring/debugging tests
|
|
391
|
+
```
|
|
392
|
+
|
|
393
|
+
Run a specific test file:
|
|
394
|
+
|
|
395
|
+
```bash
|
|
396
|
+
pnpm vitest run tests/validation/string.test.ts
|
|
397
|
+
pnpm vitest run -t "validates strings" # Run by test name pattern
|
|
398
|
+
```
|
|
399
|
+
|
|
400
|
+
### Build Commands
|
|
401
|
+
|
|
402
|
+
```bash
|
|
403
|
+
pnpm build # Compile TypeScript
|
|
404
|
+
pnpm type-check # Type check only (faster)
|
|
405
|
+
pnpm package:build # Build distributable with tsdown
|
|
406
|
+
```
|
|
407
|
+
|
|
408
|
+
### Path Aliases
|
|
409
|
+
|
|
410
|
+
```typescript
|
|
411
|
+
import { ... } from "@schema"; // src/schema/
|
|
412
|
+
import { ... } from "@client"; // src/client/
|
|
413
|
+
import { ... } from "@validation"; // src/validation/
|
|
414
|
+
import { ... } from "@query-engine"; // src/query-engine/
|
|
415
|
+
import { ... } from "@adapters"; // src/adapters/
|
|
416
|
+
import { ... } from "@drivers"; // src/drivers/
|
|
417
|
+
import { ... } from "@sql"; // src/sql/
|
|
418
|
+
```
|
|
419
|
+
|
|
420
|
+
---
|
|
421
|
+
|
|
422
|
+
## Agent-First Codebase
|
|
423
|
+
|
|
424
|
+
This codebase is designed for **AI agents to help developers**. Each major directory contains an `AGENTS.md` file—comprehensive architectural documentation that AI assistants can read to understand:
|
|
425
|
+
|
|
426
|
+
- **Why** the layer exists and what problems it solves
|
|
427
|
+
- **Entry points** and key files to modify
|
|
428
|
+
- **Core rules** that must never be broken
|
|
429
|
+
- **Anti-patterns** to avoid
|
|
430
|
+
- **Step-by-step guides** for common tasks
|
|
431
|
+
|
|
432
|
+
**Key documentation:**
|
|
433
|
+
- `AGENTS.md` — Full architectural overview (start here)
|
|
434
|
+
- `FEATURE_IMPLEMENTATION_TEMPLATE.md` — Step-by-step guide for implementing features and fixing bugs, with layer-by-layer analysis framework and code patterns
|
|
435
|
+
|
|
436
|
+
When working with an AI assistant, point it to these files first.
|
|
437
|
+
|
|
438
|
+
### Navigating the Codebase
|
|
439
|
+
|
|
440
|
+
| I want to... | Start here |
|
|
441
|
+
|--------------|------------|
|
|
442
|
+
| Add new field type | `src/schema/fields/AGENTS.md` |
|
|
443
|
+
| Add query operator | `src/query-engine/AGENTS.md` + `src/adapters/AGENTS.md` |
|
|
444
|
+
| Fix type inference bug | `src/client/AGENTS.md` → check upstream schemas |
|
|
445
|
+
| Add migration operation | `src/migrations/AGENTS.md` |
|
|
446
|
+
| Add relation feature | `src/schema/relation/AGENTS.md` |
|
|
447
|
+
| Understand validation | `src/validation/AGENTS.md` |
|
|
448
|
+
|
|
449
|
+
---
|
|
450
|
+
|
|
451
|
+
## Test Structure
|
|
452
|
+
|
|
453
|
+
Tests mirror the `src/` structure:
|
|
454
|
+
|
|
455
|
+
```
|
|
456
|
+
tests/
|
|
457
|
+
├── validation/ 28 tests for v.* primitives
|
|
458
|
+
├── fields/ Schema generation per field type
|
|
459
|
+
├── model/ Query schemas (where, create, update, args)
|
|
460
|
+
│ ├── filter/ WHERE clause generation
|
|
461
|
+
│ ├── create/ CREATE input schemas
|
|
462
|
+
│ ├── update/ UPDATE input schemas
|
|
463
|
+
│ └── args/ Operation argument schemas
|
|
464
|
+
├── query-engine/ SQL generation tests
|
|
465
|
+
├── relations/ Relation CRUD operations
|
|
466
|
+
├── client/ End-to-end client operations
|
|
467
|
+
├── migrations/ Schema diffing and DDL
|
|
468
|
+
└── drivers/ Database-specific driver tests
|
|
469
|
+
```
|
|
470
|
+
|
|
471
|
+
Most tests run against PGlite (in-memory PostgreSQL). Driver tests in `tests/drivers/` require external databases.
|
|
472
|
+
|
|
473
|
+
---
|
|
474
|
+
|
|
475
|
+
## Common Pitfalls
|
|
476
|
+
|
|
477
|
+
| Mistake | Why it breaks | Fix |
|
|
478
|
+
|---------|---------------|-----|
|
|
479
|
+
| Hardcoded SQL in query-engine | Breaks MySQL/SQLite | Use `ctx.adapter.*` methods |
|
|
480
|
+
| Type assertions (`as`) | Hides type mismatches | Let types flow naturally |
|
|
481
|
+
| Forgot Field union update | New field type invisible | Update `src/schema/fields/base.ts` |
|
|
482
|
+
| Direct model reference in relation | ReferenceError at runtime | Use thunk `() => model` |
|
|
483
|
+
| Eager schema building | Performance (rebuilds every access) | Use `??=` lazy pattern |
|
|
484
|
+
| Mutation instead of new instance | Type/runtime desync | Return new instance from modifiers |
|
|
485
|
+
|
|
486
|
+
---
|
|
487
|
+
|
|
488
|
+
## Current Status
|
|
489
|
+
|
|
490
|
+
**Core features working:**
|
|
491
|
+
- All CRUD operations (create, read, update, delete, upsert)
|
|
492
|
+
- Relations (oneToOne, oneToMany, manyToOne, manyToMany)
|
|
493
|
+
- Nested writes (connect, disconnect, create, update, delete)
|
|
494
|
+
- Select/include with typed results
|
|
495
|
+
- All field types (string, int, float, boolean, dateTime, json, enum, etc.)
|
|
496
|
+
- PostgreSQL, MySQL, and SQLite adapters
|
|
497
|
+
- Query caching with TTL and SWR
|
|
498
|
+
- Transactions (callback and batch modes)
|
|
499
|
+
- OpenTelemetry instrumentation
|
|
500
|
+
|
|
501
|
+
**Known limitations:**
|
|
502
|
+
- MySQL migrations not yet implemented
|
|
503
|
+
|
|
504
|
+
**Future features** (documented in `features-docs/`):
|
|
505
|
+
- Polymorphic relations
|
|
506
|
+
- Recursive queries (WITH RECURSIVE)
|
|
507
|
+
|
|
508
|
+
See `PENDING_WORK.md` for detailed tracking.
|
|
509
|
+
|
|
510
|
+
---
|
|
511
|
+
|
|
512
|
+
## Internal API Convention
|
|
513
|
+
|
|
514
|
+
All internal state is accessed via `["~"]`:
|
|
515
|
+
|
|
516
|
+
```typescript
|
|
517
|
+
field["~"].state // FieldState - configuration object
|
|
518
|
+
field["~"].schemas // {base, filter, create, update} - lazy built
|
|
519
|
+
model["~"].schemas.where // Where schema for this model
|
|
520
|
+
relation["~"].targetModel // Thunk to target model
|
|
521
|
+
```
|
|
522
|
+
|
|
523
|
+
This keeps the public API clean and signals "internal" to developers.
|
|
524
|
+
|
|
525
|
+
---
|
|
526
|
+
|
|
527
|
+
## License
|
|
528
|
+
|
|
529
|
+
MIT
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { _ as InsertParts, a as SchemaError, c as SQLiteAdapter, d as postgresAdapter, f as MySQLAdapter, g as DeleteParts, h as DatabaseAdapter, i as QueryError, l as sqliteAdapter, m as CastType, n as AdapterError, o as ValidationError, p as mysqlAdapter, r as ConnectionError, s as ValidationRule, t as ASTError, u as PostgresAdapter, v as QueryParts, y as UpdateParts } from "./index-BGmpst1h.mjs";
|
|
2
|
+
export { ASTError, AdapterError, CastType, ConnectionError, DatabaseAdapter, DeleteParts, InsertParts, MySQLAdapter, PostgresAdapter, QueryError, QueryParts, SQLiteAdapter, SchemaError, UpdateParts, ValidationError, ValidationRule, mysqlAdapter, postgresAdapter, sqliteAdapter };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e,t}from"./postgres-adapter-Blzqj1bl.mjs";import{n,t as r}from"./mysql-adapter-0catKeCI.mjs";import{n as i,t as a}from"./sqlite-adapter-5Em_-oGU.mjs";export{r as MySQLAdapter,t as PostgresAdapter,a as SQLiteAdapter,n as mysqlAdapter,e as postgresAdapter,i as sqliteAdapter};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import "./index-BGmpst1h.mjs";
|
|
2
|
+
import { At as createClient, Dt as BunSQLDriver, Et as BunSQLClientConfig, Ot as BunSQLDriverOptions, kt as BunSQLOptions } from "./cloudflare-kv-DauXhtnT.mjs";
|
|
3
|
+
export { BunSQLClientConfig, BunSQLDriver, BunSQLDriverOptions, BunSQLOptions, createClient };
|
package/dist/bun-sql.mjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{C as e,S as t}from"./errors-DvcqIdEo.mjs";import{t as n}from"./client-CgdtiDGV.mjs";import{t as r}from"./driver-Cj1EbciY.mjs";import{t as i}from"./postgres-adapter-Blzqj1bl.mjs";var a=class extends r{constructor(n={}){super(`postgresql`,`bun-sql`),this.driverOptions=n,n.client&&(this.client=n.client);let r=new i;n.pgvector||(r.vector=e),n.postgis||(r.geospatial=t),this.adapter=r}async initClient(){let{SQL:e}=await import(`bun:sql`);return this.driverOptions.databaseUrl?new e(this.driverOptions.databaseUrl):new e(this.driverOptions.options??{})}async closeClient(e){e.close()}async execute(e,t,n){let r=await e.unsafe(t,n);return{rows:r,rowCount:r.length}}async executeRaw(e,t,n){let r=await e.unsafe(t,n);return{rows:r,rowCount:r.length}}async transaction(e,t,n){if(`savepoint`in e)return e.savepoint(t);let r=e;if(n?.isolationLevel){let e={read_uncommitted:`READ UNCOMMITTED`,read_committed:`READ COMMITTED`,repeatable_read:`REPEATABLE READ`,serializable:`SERIALIZABLE`}[n.isolationLevel];if(!e)throw Error(`Unknown isolation level: ${n.isolationLevel}`);return r.begin(async n=>(await n.unsafe(`SET TRANSACTION ISOLATION LEVEL ${e}`),t(n)))}return r.begin(t)}};function o(e){let{client:t,databaseUrl:r,options:i,pgvector:o,postgis:s,...c}=e,l=new a({client:t,databaseUrl:r,options:i,pgvector:o,postgis:s});return n({...c,driver:l})}export{a as BunSQLDriver,o as createClient};
|
|
2
|
+
//# sourceMappingURL=bun-sql.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bun-sql.mjs","names":["baseCreateClient"],"sources":["../src/drivers/bun-sql/index.ts"],"sourcesContent":["/**\n * Bun SQL Driver\n *\n * Driver implementation for Bun's built-in PostgreSQL client (bun:sql).\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport { PostgresAdapter } from \"@adapters/databases/postgres/postgres-adapter\";\nimport {\n createClient as baseCreateClient,\n type DriverConfig,\n type VibORMClient,\n} from \"@client/client\";\nimport { unsupportedGeospatial, unsupportedVector } from \"@errors\";\nimport { Driver } from \"../driver\";\nimport type { QueryResult, TransactionOptions } from \"../types\";\n\n// ============================================================\n// TYPE DECLARATIONS FOR BUN:SQL\n// ============================================================\n\n// Bun's SQL type - we define inline to avoid requiring bun types at compile time\ninterface BunSQL {\n (strings: TemplateStringsArray, ...values: unknown[]): Promise<unknown[]>;\n unsafe<T = unknown>(sql: string, params?: unknown[]): Promise<T[]>;\n begin<T>(fn: (sql: BunSQLTransaction) => Promise<T>): Promise<T>;\n close(): void;\n reserve(): Promise<BunSQLReservedConnection>;\n}\n\ninterface BunSQLTransaction {\n (strings: TemplateStringsArray, ...values: unknown[]): Promise<unknown[]>;\n unsafe<T = unknown>(sql: string, params?: unknown[]): Promise<T[]>;\n savepoint<T>(fn: (sql: BunSQLTransaction) => Promise<T>): Promise<T>;\n}\n\ninterface BunSQLReservedConnection {\n (strings: TemplateStringsArray, ...values: unknown[]): Promise<unknown[]>;\n unsafe<T = unknown>(sql: string, params?: unknown[]): Promise<T[]>;\n release(): void;\n}\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport interface BunSQLOptions {\n hostname?: string;\n port?: number;\n username?: string;\n password?: string;\n database?: string;\n tls?: boolean | object;\n max?: number;\n idleTimeout?: number;\n maxLifetime?: number;\n}\n\nexport interface BunSQLDriverOptions {\n client?: BunSQL;\n databaseUrl?: string;\n options?: BunSQLOptions;\n pgvector?: boolean;\n postgis?: boolean;\n}\n\nexport type BunSQLClientConfig<C extends DriverConfig> = BunSQLDriverOptions &\n C;\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class BunSQLDriver extends Driver<BunSQL, BunSQLTransaction> {\n readonly adapter: DatabaseAdapter;\n\n private readonly driverOptions: BunSQLDriverOptions;\n\n constructor(options: BunSQLDriverOptions = {}) {\n super(\"postgresql\", \"bun-sql\");\n this.driverOptions = options;\n\n if (options.client) {\n this.client = options.client;\n }\n\n const adapter = new PostgresAdapter();\n if (!options.pgvector) adapter.vector = unsupportedVector;\n if (!options.postgis) adapter.geospatial = unsupportedGeospatial;\n this.adapter = adapter;\n }\n\n protected async initClient(): Promise<BunSQL> {\n // bun:sql is a Bun-only built-in module - types may not be available at compile time\n // @ts-expect-error - bun:sql is only available in Bun runtime\n const { SQL } = await import(\"bun:sql\");\n\n if (this.driverOptions.databaseUrl) {\n return new SQL(this.driverOptions.databaseUrl) as unknown as BunSQL;\n }\n\n return new SQL(this.driverOptions.options ?? {}) as unknown as BunSQL;\n }\n\n protected async closeClient(sql: BunSQL): Promise<void> {\n sql.close();\n }\n\n protected async execute<T>(\n client: BunSQL | BunSQLTransaction,\n sql: string,\n params: unknown[]\n ): Promise<QueryResult<T>> {\n const result = await client.unsafe<T>(sql, params);\n return {\n rows: result,\n rowCount: result.length,\n };\n }\n\n protected async executeRaw<T>(\n client: BunSQL | BunSQLTransaction,\n sql: string,\n params?: unknown[]\n ): Promise<QueryResult<T>> {\n const result = await client.unsafe<T>(sql, params);\n return {\n rows: result,\n rowCount: result.length,\n };\n }\n\n protected async transaction<T>(\n client: BunSQL | BunSQLTransaction,\n fn: (tx: BunSQLTransaction) => Promise<T>,\n options?: TransactionOptions\n ): Promise<T> {\n // Check if we're already in a transaction\n if (\"savepoint\" in client) {\n // Nested transaction - use savepoint\n const tx = client as BunSQLTransaction;\n return tx.savepoint(fn);\n }\n\n // Start new transaction\n const sql = client as BunSQL;\n\n // Bun SQL's begin() doesn't support isolation level as argument\n // Set it manually before the transaction if specified\n if (options?.isolationLevel) {\n const isolationMap: Record<string, string> = {\n read_uncommitted: \"READ UNCOMMITTED\",\n read_committed: \"READ COMMITTED\",\n repeatable_read: \"REPEATABLE READ\",\n serializable: \"SERIALIZABLE\",\n };\n const level = isolationMap[options.isolationLevel];\n if (!level) {\n throw new Error(`Unknown isolation level: ${options.isolationLevel}`);\n }\n return sql.begin(async (tx) => {\n await tx.unsafe(`SET TRANSACTION ISOLATION LEVEL ${level}`);\n return fn(tx);\n });\n }\n\n return sql.begin(fn);\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<C extends DriverConfig>(\n config: BunSQLClientConfig<C>\n) {\n const { client, databaseUrl, options, pgvector, postgis, ...restConfig } =\n config;\n\n const driver = new BunSQLDriver({\n client,\n databaseUrl,\n options,\n pgvector,\n postgis,\n });\n\n return baseCreateClient({\n ...restConfig,\n driver,\n }) as VibORMClient<C & { driver: BunSQLDriver }>;\n}\n"],"mappings":"yLAyEA,IAAa,EAAb,cAAkC,CAAkC,CAKlE,YAAY,EAA+B,EAAE,CAAE,CAC7C,MAAM,aAAc,UAAU,CAC9B,KAAK,cAAgB,EAEjB,EAAQ,SACV,KAAK,OAAS,EAAQ,QAGxB,IAAM,EAAU,IAAI,EACf,EAAQ,WAAU,EAAQ,OAAS,GACnC,EAAQ,UAAS,EAAQ,WAAa,GAC3C,KAAK,QAAU,EAGjB,MAAgB,YAA8B,CAG5C,GAAM,CAAE,OAAQ,MAAM,OAAO,WAM7B,OAJI,KAAK,cAAc,YACd,IAAI,EAAI,KAAK,cAAc,YAAY,CAGzC,IAAI,EAAI,KAAK,cAAc,SAAW,EAAE,CAAC,CAGlD,MAAgB,YAAY,EAA4B,CACtD,EAAI,OAAO,CAGb,MAAgB,QACd,EACA,EACA,EACyB,CACzB,IAAM,EAAS,MAAM,EAAO,OAAU,EAAK,EAAO,CAClD,MAAO,CACL,KAAM,EACN,SAAU,EAAO,OAClB,CAGH,MAAgB,WACd,EACA,EACA,EACyB,CACzB,IAAM,EAAS,MAAM,EAAO,OAAU,EAAK,EAAO,CAClD,MAAO,CACL,KAAM,EACN,SAAU,EAAO,OAClB,CAGH,MAAgB,YACd,EACA,EACA,EACY,CAEZ,GAAI,cAAe,EAGjB,OADW,EACD,UAAU,EAAG,CAIzB,IAAM,EAAM,EAIZ,GAAI,GAAS,eAAgB,CAO3B,IAAM,EANuC,CAC3C,iBAAkB,mBAClB,eAAgB,iBAChB,gBAAiB,kBACjB,aAAc,eACf,CAC0B,EAAQ,gBACnC,GAAI,CAAC,EACH,MAAU,MAAM,4BAA4B,EAAQ,iBAAiB,CAEvE,OAAO,EAAI,MAAM,KAAO,KACtB,MAAM,EAAG,OAAO,mCAAmC,IAAQ,CACpD,EAAG,EAAG,EACb,CAGJ,OAAO,EAAI,MAAM,EAAG,GAQxB,SAAgB,EACd,EACA,CACA,GAAM,CAAE,SAAQ,cAAa,UAAS,WAAU,UAAS,GAAG,GAC1D,EAEI,EAAS,IAAI,EAAa,CAC9B,SACA,cACA,UACA,WACA,UACD,CAAC,CAEF,OAAOA,EAAiB,CACtB,GAAG,EACH,SACD,CAAC"}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import "./index-BGmpst1h.mjs";
|
|
2
|
+
import { Ct as BunSQLiteDriverOptions, St as BunSQLiteDriver, Tt as createClient, wt as BunSQLiteOptions, xt as BunSQLiteClientConfig } from "./cloudflare-kv-DauXhtnT.mjs";
|
|
3
|
+
export { BunSQLiteClientConfig, BunSQLiteDriver, BunSQLiteDriverOptions, BunSQLiteOptions, createClient };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{t as e}from"./client-CgdtiDGV.mjs";import{t}from"./driver-Cj1EbciY.mjs";import{n,t as r}from"./sqlite-utils-BW7elKTz.mjs";import{t as i}from"./sqlite-adapter-5Em_-oGU.mjs";var a=class extends t{constructor(e={}){super(`sqlite`,`bun-sqlite`),this.adapter=new i,this.result=n,this.driverOptions=e,e.client&&(this.client=e.client)}async initClient(){let{Database:e}=await import(`bun:sqlite`);return new e(this.driverOptions.dataDir??`:memory:`,this.driverOptions.options??{})}async closeClient(e){e.close()}async execute(e,t,n){let i=r(n);return this.runStatement(e,t,i)}async executeRaw(e,t,n){let i=n?r(n):void 0;return this.runStatement(e,t,i)}runStatement(e,t,n){let r=e.prepare(t),i=t.trim().toUpperCase(),a=i.startsWith(`SELECT`)||i.startsWith(`WITH`),o=i.includes(`RETURNING`);if(a||o){let e=n?r.all(...n):r.all();return{rows:e,rowCount:e.length}}return{rows:[],rowCount:(n?r.run(...n):r.run()).changes}}async transaction(e,t,n){if(this.inTransaction){let n=`sp_${crypto.randomUUID().replace(/-/g,``)}`;e.exec(`SAVEPOINT ${n}`);try{let r=await t(e);return e.exec(`RELEASE SAVEPOINT ${n}`),r}catch(t){throw e.exec(`ROLLBACK TO SAVEPOINT ${n}`),t}}e.exec(`BEGIN`),this.inTransaction=!0;try{let n=await t(e);return e.exec(`COMMIT`),n}catch(t){throw e.exec(`ROLLBACK`),t}}};function o(t){let{client:n,dataDir:r,options:i,...o}=t,s=new a({client:n,dataDir:r,options:i});return e({...o,driver:s})}export{a as BunSQLiteDriver,o as createClient};
|
|
2
|
+
//# sourceMappingURL=bun-sqlite.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bun-sqlite.mjs","names":["baseCreateClient"],"sources":["../src/drivers/bun-sqlite/index.ts"],"sourcesContent":["/**\n * Bun SQLite Driver\n *\n * Driver implementation for Bun's built-in SQLite (bun:sqlite).\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport { SQLiteAdapter } from \"@adapters/databases/sqlite/sqlite-adapter\";\nimport {\n createClient as baseCreateClient,\n type DriverConfig,\n type VibORMClient,\n} from \"@client/client\";\nimport { Driver, type DriverResultParser } from \"../driver\";\nimport { convertValuesForSQLite, sqliteResultParser } from \"../shared\";\nimport type { QueryResult, TransactionOptions } from \"../types\";\n\n// ============================================================\n// TYPE DECLARATIONS FOR BUN:SQLITE\n// ============================================================\n\n// Bun's Database type - we define inline to avoid requiring bun types at compile time\ninterface BunSQLiteDatabase {\n query<T = unknown>(sql: string): BunSQLiteStatement<T>;\n prepare<T = unknown>(sql: string): BunSQLiteStatement<T>;\n run(sql: string, ...params: unknown[]): void;\n exec(sql: string): void;\n close(): void;\n transaction<T>(fn: () => T): () => T;\n}\n\ninterface BunSQLiteStatement<T = unknown> {\n all(...params: unknown[]): T[];\n get(...params: unknown[]): T | null;\n run(...params: unknown[]): {\n changes: number;\n lastInsertRowid: number | bigint;\n };\n values(...params: unknown[]): unknown[][];\n}\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport interface BunSQLiteOptions {\n readonly?: boolean;\n create?: boolean;\n readwrite?: boolean;\n strict?: boolean;\n}\n\nexport interface BunSQLiteDriverOptions {\n client?: BunSQLiteDatabase;\n dataDir?: string;\n options?: BunSQLiteOptions;\n}\n\nexport type BunSQLiteClientConfig<C extends DriverConfig> =\n BunSQLiteDriverOptions & C;\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class BunSQLiteDriver extends Driver<\n BunSQLiteDatabase,\n BunSQLiteDatabase\n> {\n readonly adapter: DatabaseAdapter = new SQLiteAdapter();\n readonly result: DriverResultParser = sqliteResultParser;\n\n private readonly driverOptions: BunSQLiteDriverOptions;\n\n constructor(options: BunSQLiteDriverOptions = {}) {\n super(\"sqlite\", \"bun-sqlite\");\n this.driverOptions = options;\n\n if (options.client) {\n this.client = options.client;\n }\n }\n\n protected async initClient(): Promise<BunSQLiteDatabase> {\n // Dynamic import for bun:sqlite\n const { Database } = await import(\"bun:sqlite\");\n\n const dataDir = this.driverOptions.dataDir ?? \":memory:\";\n const options = this.driverOptions.options ?? {};\n\n return new Database(dataDir, options) as unknown as BunSQLiteDatabase;\n }\n\n protected async closeClient(db: BunSQLiteDatabase): Promise<void> {\n db.close();\n }\n\n protected async execute<T>(\n client: BunSQLiteDatabase,\n sql: string,\n params: unknown[]\n ): Promise<QueryResult<T>> {\n const values = convertValuesForSQLite(params);\n return this.runStatement<T>(client, sql, values);\n }\n\n protected async executeRaw<T>(\n client: BunSQLiteDatabase,\n sql: string,\n params?: unknown[]\n ): Promise<QueryResult<T>> {\n const values = params ? convertValuesForSQLite(params) : undefined;\n return this.runStatement<T>(client, sql, values);\n }\n\n private runStatement<T>(\n db: BunSQLiteDatabase,\n sql: string,\n values?: unknown[]\n ): QueryResult<T> {\n const stmt = db.prepare(sql);\n const normalized = sql.trim().toUpperCase();\n const isSelect =\n normalized.startsWith(\"SELECT\") || normalized.startsWith(\"WITH\");\n const isReturning = normalized.includes(\"RETURNING\");\n\n if (isSelect || isReturning) {\n const rows = (values ? stmt.all(...values) : stmt.all()) as T[];\n return { rows, rowCount: rows.length };\n }\n\n const result = values ? stmt.run(...values) : stmt.run();\n return { rows: [] as T[], rowCount: result.changes };\n }\n\n protected async transaction<T>(\n client: BunSQLiteDatabase,\n fn: (tx: BunSQLiteDatabase) => Promise<T>,\n _options?: TransactionOptions\n ): Promise<T> {\n if (this.inTransaction) {\n // Nested transaction - use savepoint\n const savepointName = `sp_${crypto.randomUUID().replace(/-/g, \"\")}`;\n client.exec(`SAVEPOINT ${savepointName}`);\n try {\n const result = await fn(client);\n client.exec(`RELEASE SAVEPOINT ${savepointName}`);\n return result;\n } catch (error) {\n client.exec(`ROLLBACK TO SAVEPOINT ${savepointName}`);\n throw error;\n }\n }\n\n // Start a new transaction\n client.exec(\"BEGIN\");\n this.inTransaction = true;\n try {\n const result = await fn(client);\n client.exec(\"COMMIT\");\n return result;\n } catch (error) {\n client.exec(\"ROLLBACK\");\n throw error;\n }\n // Note: this.inTransaction reset is handled by base Driver._transaction()\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<C extends DriverConfig>(\n config: BunSQLiteClientConfig<C>\n) {\n const { client, dataDir, options, ...restConfig } = config;\n\n const driver = new BunSQLiteDriver({ client, dataDir, options });\n\n return baseCreateClient({\n ...restConfig,\n driver,\n }) as VibORMClient<C & { driver: BunSQLiteDriver }>;\n}\n"],"mappings":"mLAiEA,IAAa,EAAb,cAAqC,CAGnC,CAMA,YAAY,EAAkC,EAAE,CAAE,CAChD,MAAM,SAAU,aAAa,cANK,IAAI,cACF,EAMpC,KAAK,cAAgB,EAEjB,EAAQ,SACV,KAAK,OAAS,EAAQ,QAI1B,MAAgB,YAAyC,CAEvD,GAAM,CAAE,YAAa,MAAM,OAAO,cAKlC,OAAO,IAAI,EAHK,KAAK,cAAc,SAAW,WAC9B,KAAK,cAAc,SAAW,EAAE,CAEX,CAGvC,MAAgB,YAAY,EAAsC,CAChE,EAAG,OAAO,CAGZ,MAAgB,QACd,EACA,EACA,EACyB,CACzB,IAAM,EAAS,EAAuB,EAAO,CAC7C,OAAO,KAAK,aAAgB,EAAQ,EAAK,EAAO,CAGlD,MAAgB,WACd,EACA,EACA,EACyB,CACzB,IAAM,EAAS,EAAS,EAAuB,EAAO,CAAG,IAAA,GACzD,OAAO,KAAK,aAAgB,EAAQ,EAAK,EAAO,CAGlD,aACE,EACA,EACA,EACgB,CAChB,IAAM,EAAO,EAAG,QAAQ,EAAI,CACtB,EAAa,EAAI,MAAM,CAAC,aAAa,CACrC,EACJ,EAAW,WAAW,SAAS,EAAI,EAAW,WAAW,OAAO,CAC5D,EAAc,EAAW,SAAS,YAAY,CAEpD,GAAI,GAAY,EAAa,CAC3B,IAAM,EAAQ,EAAS,EAAK,IAAI,GAAG,EAAO,CAAG,EAAK,KAAK,CACvD,MAAO,CAAE,OAAM,SAAU,EAAK,OAAQ,CAIxC,MAAO,CAAE,KAAM,EAAE,CAAS,UADX,EAAS,EAAK,IAAI,GAAG,EAAO,CAAG,EAAK,KAAK,EACb,QAAS,CAGtD,MAAgB,YACd,EACA,EACA,EACY,CACZ,GAAI,KAAK,cAAe,CAEtB,IAAM,EAAgB,MAAM,OAAO,YAAY,CAAC,QAAQ,KAAM,GAAG,GACjE,EAAO,KAAK,aAAa,IAAgB,CACzC,GAAI,CACF,IAAM,EAAS,MAAM,EAAG,EAAO,CAE/B,OADA,EAAO,KAAK,qBAAqB,IAAgB,CAC1C,QACA,EAAO,CAEd,MADA,EAAO,KAAK,yBAAyB,IAAgB,CAC/C,GAKV,EAAO,KAAK,QAAQ,CACpB,KAAK,cAAgB,GACrB,GAAI,CACF,IAAM,EAAS,MAAM,EAAG,EAAO,CAE/B,OADA,EAAO,KAAK,SAAS,CACd,QACA,EAAO,CAEd,MADA,EAAO,KAAK,WAAW,CACjB,KAUZ,SAAgB,EACd,EACA,CACA,GAAM,CAAE,SAAQ,UAAS,UAAS,GAAG,GAAe,EAE9C,EAAS,IAAI,EAAgB,CAAE,SAAQ,UAAS,UAAS,CAAC,CAEhE,OAAOA,EAAiB,CACtB,GAAG,EACH,SACD,CAAC"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{t as e}from"../driver-B_vBzQ6A.mjs";var t=class extends e{constructor(e){super(`cloudflare-kv`),this.kv=e}async get(e){return await this.kv.get(e,`json`)||null}async set(e,t,n){let r=Math.ceil(t/1e3);await this.kv.put(e,JSON.stringify(n),{expirationTtl:r})}async delete(e){await Promise.all(e.map(e=>this.kv.delete(e)))}async clear(e){let t;do{let n=await this.kv.list({prefix:e,cursor:t});await Promise.all(n.keys.map(e=>this.kv.delete(e.name))),t=n.list_complete?void 0:n.cursor}while(t)}};export{t as CloudflareKVCache};
|
|
2
|
+
//# sourceMappingURL=cloudflare-kv.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cloudflare-kv.mjs","names":[],"sources":["../../src/cache/drivers/cloudflare-kv.ts"],"sourcesContent":["/**\n * Cloudflare KV Cache\n *\n * Cache implementation using Cloudflare Workers KV.\n */\n\nimport type { KVNamespace } from \"@cloudflare/workers-types\";\nimport { CacheDriver, type CacheEntry } from \"../driver\";\n\n/**\n * Cloudflare KV cache implementation\n */\nexport class CloudflareKVCache extends CacheDriver {\n private readonly kv: KVNamespace;\n\n constructor(kv: KVNamespace) {\n super(\"cloudflare-kv\");\n this.kv = kv;\n }\n\n protected async get<T>(key: string): Promise<CacheEntry<T> | null> {\n const data = await this.kv.get<CacheEntry<T>>(key, \"json\");\n if (!data) return null;\n return data;\n }\n\n protected async set<T>(\n key: string,\n storageTtl: number,\n entry: CacheEntry<T>\n ): Promise<void> {\n // KV TTL is in seconds\n const kvTtlSeconds = Math.ceil(storageTtl / 1000);\n\n await this.kv.put(key, JSON.stringify(entry), {\n expirationTtl: kvTtlSeconds,\n });\n }\n\n protected async delete(keys: string[]): Promise<void> {\n await Promise.all(keys.map((key) => this.kv.delete(key)));\n }\n\n protected async clear(prefix: string): Promise<void> {\n let cursor: string | undefined;\n do {\n const result = await this.kv.list({ prefix, cursor });\n await Promise.all(result.keys.map((k) => this.kv.delete(k.name)));\n cursor = result.list_complete ? undefined : result.cursor;\n } while (cursor);\n }\n}\n"],"mappings":"2CAYA,IAAa,EAAb,cAAuC,CAAY,CAGjD,YAAY,EAAiB,CAC3B,MAAM,gBAAgB,CACtB,KAAK,GAAK,EAGZ,MAAgB,IAAO,EAA4C,CAGjE,OAFa,MAAM,KAAK,GAAG,IAAmB,EAAK,OAAO,EACxC,KAIpB,MAAgB,IACd,EACA,EACA,EACe,CAEf,IAAM,EAAe,KAAK,KAAK,EAAa,IAAK,CAEjD,MAAM,KAAK,GAAG,IAAI,EAAK,KAAK,UAAU,EAAM,CAAE,CAC5C,cAAe,EAChB,CAAC,CAGJ,MAAgB,OAAO,EAA+B,CACpD,MAAM,QAAQ,IAAI,EAAK,IAAK,GAAQ,KAAK,GAAG,OAAO,EAAI,CAAC,CAAC,CAG3D,MAAgB,MAAM,EAA+B,CACnD,IAAI,EACJ,EAAG,CACD,IAAM,EAAS,MAAM,KAAK,GAAG,KAAK,CAAE,SAAQ,SAAQ,CAAC,CACrD,MAAM,QAAQ,IAAI,EAAO,KAAK,IAAK,GAAM,KAAK,GAAG,OAAO,EAAE,KAAK,CAAC,CAAC,CACjE,EAAS,EAAO,cAAgB,IAAA,GAAY,EAAO,aAC5C"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{t as e}from"../driver-B_vBzQ6A.mjs";var t=class extends e{constructor(){super(`memory`),this.store=new Map,this.timers=new Map}async get(e){return this.store.get(e)||null}async set(e,t,n){this.clearTimer(e),this.store.set(e,n);let r=setTimeout(()=>{this.store.delete(e),this.timers.delete(e)},t);typeof r.unref==`function`&&r.unref(),this.timers.set(e,r)}async delete(e){for(let t of e)this.clearTimer(t),this.store.delete(t)}async clear(e){for(let t of this.store.keys())t.startsWith(e)&&(this.clearTimer(t),this.store.delete(t))}clearTimer(e){let t=this.timers.get(e);t&&(clearTimeout(t),this.timers.delete(e))}};export{t as MemoryCache};
|
|
2
|
+
//# sourceMappingURL=memory.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"memory.mjs","names":[],"sources":["../../src/cache/drivers/memory.ts"],"sourcesContent":["/**\n * Memory Cache\n *\n * In-memory cache implementation for development/testing.\n * Suitable for single-instance deployments.\n *\n * @example\n * ```ts\n * // Direct import for optimal tree-shaking\n * import { MemoryCache } from \"viborm/cache/memory\";\n *\n * const client = createClient({\n * schema,\n * driver,\n * cache: new MemoryCache(),\n * });\n * ```\n */\n\nimport { CacheDriver, type CacheEntry } from \"../driver\";\n\n/**\n * In-memory cache implementation\n */\nexport class MemoryCache extends CacheDriver {\n private readonly store = new Map<string, CacheEntry>();\n private readonly timers = new Map<string, ReturnType<typeof setTimeout>>();\n\n constructor() {\n super(\"memory\");\n }\n\n protected async get<T>(key: string): Promise<CacheEntry<T> | null> {\n const entry = this.store.get(key);\n if (!entry) return null;\n return entry as CacheEntry<T>;\n }\n\n protected async set<T>(\n key: string,\n storageTtl: number,\n entry: CacheEntry<T>\n ): Promise<void> {\n // Clear existing timer if re-setting key\n this.clearTimer(key);\n this.store.set(key, entry);\n // Schedule cleanup after storageTtl to prevent unbounded growth\n const timer = setTimeout(() => {\n this.store.delete(key);\n this.timers.delete(key);\n }, storageTtl);\n if (typeof timer.unref === \"function\") timer.unref();\n this.timers.set(key, timer);\n }\n\n protected async delete(keys: string[]): Promise<void> {\n for (const key of keys) {\n this.clearTimer(key);\n this.store.delete(key);\n }\n }\n\n protected async clear(prefix: string): Promise<void> {\n for (const key of this.store.keys()) {\n if (key.startsWith(prefix)) {\n this.clearTimer(key);\n this.store.delete(key);\n }\n }\n }\n\n private clearTimer(key: string): void {\n const timer = this.timers.get(key);\n if (timer) {\n clearTimeout(timer);\n this.timers.delete(key);\n }\n }\n}\n"],"mappings":"2CAwBA,IAAa,EAAb,cAAiC,CAAY,CAI3C,aAAc,CACZ,MAAM,SAAS,YAJQ,IAAI,gBACH,IAAI,IAM9B,MAAgB,IAAO,EAA4C,CAGjE,OAFc,KAAK,MAAM,IAAI,EAAI,EACd,KAIrB,MAAgB,IACd,EACA,EACA,EACe,CAEf,KAAK,WAAW,EAAI,CACpB,KAAK,MAAM,IAAI,EAAK,EAAM,CAE1B,IAAM,EAAQ,eAAiB,CAC7B,KAAK,MAAM,OAAO,EAAI,CACtB,KAAK,OAAO,OAAO,EAAI,EACtB,EAAW,CACV,OAAO,EAAM,OAAU,YAAY,EAAM,OAAO,CACpD,KAAK,OAAO,IAAI,EAAK,EAAM,CAG7B,MAAgB,OAAO,EAA+B,CACpD,IAAK,IAAM,KAAO,EAChB,KAAK,WAAW,EAAI,CACpB,KAAK,MAAM,OAAO,EAAI,CAI1B,MAAgB,MAAM,EAA+B,CACnD,IAAK,IAAM,KAAO,KAAK,MAAM,MAAM,CAC7B,EAAI,WAAW,EAAO,GACxB,KAAK,WAAW,EAAI,CACpB,KAAK,MAAM,OAAO,EAAI,EAK5B,WAAmB,EAAmB,CACpC,IAAM,EAAQ,KAAK,OAAO,IAAI,EAAI,CAC9B,IACF,aAAa,EAAM,CACnB,KAAK,OAAO,OAAO,EAAI"}
|
package/dist/cache.d.mts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import "./index-BGmpst1h.mjs";
|
|
2
|
+
import { d as DEFAULT_CACHE_TTL, f as WithCacheOptions, h as withCacheSchema, l as CacheInvalidationOptions, m as cacheInvalidationSchema, p as WithCacheSchema, u as CacheInvalidationSchema } from "./helper-cDCDjRAD.mjs";
|
|
3
|
+
import { Mt as CACHE_PREFIX, Nt as generateCacheKey, Pt as generateCachePrefix, a as CacheExecutionOptions, i as CacheEntry, jt as parseTTL, n as AnyCacheDriver, o as CacheSetOptions, r as CacheDriver } from "./cloudflare-kv-DauXhtnT.mjs";
|
|
4
|
+
export { type AnyCacheDriver, CACHE_PREFIX, CacheDriver, type CacheEntry, type CacheExecutionOptions, type CacheInvalidationOptions, type CacheInvalidationSchema, type CacheSetOptions, DEFAULT_CACHE_TTL, type WithCacheOptions, type WithCacheSchema, cacheInvalidationSchema, generateCacheKey, generateCachePrefix, parseTTL, withCacheSchema };
|
package/dist/cache.mjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{i as e,n as t,r as n,t as r}from"./driver-B_vBzQ6A.mjs";import{i,n as a,r as o,t as s}from"./schema-DeAJZocc.mjs";export{t as CACHE_PREFIX,r as CacheDriver,s as DEFAULT_CACHE_TTL,a as cacheInvalidationSchema,n as generateCacheKey,e as generateCachePrefix,i as parseTTL,o as withCacheSchema};
|
package/dist/cli.d.mts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { };
|