litedbmodel-gen 0.3.3 → 0.5.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 CHANGED
@@ -1,12 +1,180 @@
1
1
  # litedbmodel-gen
2
2
 
3
- [embedoc](https://www.npmjs.com/package/embedoc)-based model code generator for [litedbmodel](https://www.npmjs.com/package/litedbmodel). Parses SQL DDL (PostgreSQL / MySQL / SQLite) and generates TypeScript column definitions that stay in sync with your schema.
3
+ [![npm version](https://img.shields.io/npm/v/litedbmodel-gen.svg)](https://www.npmjs.com/package/litedbmodel-gen)
4
4
 
5
- ## How It Works
5
+ Code generator and LLM-powered development assistant for [litedbmodel](https://www.npmjs.com/package/litedbmodel).
6
6
 
7
- litedbmodel-gen provides two embedoc plugins:
7
+ - **Generate** — Parse SQL DDL and generate type-safe model definitions that stay in sync with your schema
8
+ - **Implement** — Describe a feature and get AI-generated code that follows litedbmodel best practices
9
+ - **Audit** — Scan existing code for common litedbmodel anti-patterns and get actionable fixes
8
10
 
9
- 1. **Custom Datasource** (`sql_schema`) — reads and parses a `schema.sql` file into structured table definitions
11
+ ## Quick Start
12
+
13
+ ```bash
14
+ npm install -D litedbmodel-gen embedoc
15
+ npx embedoc init && npx litedbmodel-gen init
16
+
17
+ # Generate model definitions from schema.sql
18
+ npx embedoc generate --datasource schema
19
+ npx embedoc build
20
+
21
+ # Implement a feature using litedbmodel best practices
22
+ npx litedbmodel-gen implement \
23
+ "Add a syncNutrientSummary function in src/services/meal.service.ts that:
24
+ - Takes userId and mealDate as arguments
25
+ - Finds all Meal records for the user+date, groups by meal_type
26
+ - Aggregates nutrients per meal_type
27
+ - Upserts into MealNutrientSummary (unique on user_id, meal_date, meal_type)
28
+ - Deletes orphan summaries for meal_types that no longer have meals
29
+ - Wraps everything in a transaction with row locking" \
30
+ --target src/services/meal.service.ts \
31
+ --models "src/models/**/*.ts" --adapter claude
32
+
33
+ # Audit existing code for anti-patterns
34
+ npx litedbmodel-gen audit src/services/ --adapter claude
35
+ ```
36
+
37
+ ---
38
+
39
+ ## LLM-Powered Commands
40
+
41
+ litedbmodel-gen includes two LLM-powered commands that understand the litedbmodel API and enforce correct usage patterns. These commands are backed by [agent-contracts-runtime](https://www.npmjs.com/package/agent-contracts-runtime) and require an LLM adapter (`--adapter claude`, `openai`, `gemini`, or `cursor`).
42
+
43
+ ### Why
44
+
45
+ AI coding assistants frequently produce incorrect litedbmodel code. Common mistakes include:
46
+
47
+ | Anti-Pattern | What the AI does | What it should do |
48
+ |---|---|---|
49
+ | **LOOP_CREATE** | `for (...) { Model.create(...) }` | `Model.createMany(rows)` |
50
+ | **DELETE_REINSERT** | Delete all, then re-insert in a loop | `createMany` with `onConflict` + `onConflictUpdate` (upsert) |
51
+ | **MISSING_IDEMPOTENCY** | Bare `create()` that throws on duplicates | `create({ onConflict, onConflictIgnore: true })` |
52
+ | **N_PLUS_ONE** | `find`/`findOne` inside a loop | Batch fetch with `find` using IN conditions |
53
+ | **MISSING_LOCK** | Read-then-write without locking | `findOne(..., { forUpdate: true })` inside `DBModel.transaction()` |
54
+ | **OVER_DELETE** | `delete` with overly broad conditions | Pinpoint delete targeting only the intended rows |
55
+ | **UNIQUE_MISSING** | `onConflict` without a UNIQUE constraint in the DB | Add UNIQUE constraint via migration |
56
+ | **AGGREGATE_SKIP** | Insert raw data without aggregation | Group-by in application code, then upsert |
57
+
58
+ The `implement` and `audit` commands have deep knowledge of the litedbmodel API and proactively avoid these patterns.
59
+
60
+ ### `litedbmodel-gen implement <description>`
61
+
62
+ Implements the described feature directly in your project files using an agentic LLM adapter. The agent reads your model definitions to understand available models, then reads and edits the target source file(s).
63
+
64
+ The `<description>` argument should specify **what function to write, where to put it, and the business logic** — the more concrete, the better. Use `--target` to specify the source file to create or edit.
65
+
66
+ ```bash
67
+ npx litedbmodel-gen implement \
68
+ "Add a processOrderItems function that:
69
+ - Takes an orderId and an array of {productId, quantity, unitPrice}
70
+ - Upserts into OrderItem using (order_id, product_id) as conflict key
71
+ - Deletes OrderItem rows for productIds not in the input array
72
+ - Returns the updated order items
73
+ - Wraps all writes in a transaction" \
74
+ --target src/services/order.service.ts \
75
+ --models "src/models/**/*.ts" \
76
+ --adapter claude
77
+
78
+ # Preview the full prompt without calling the LLM
79
+ npx litedbmodel-gen implement "Add bulk user import" \
80
+ --target src/services/user.service.ts --dry-run
81
+
82
+ # Write result to a file
83
+ npx litedbmodel-gen implement "..." --target src/services/foo.ts --adapter claude -o result.json
84
+ ```
85
+
86
+ | Option | Default | Description |
87
+ |--------|---------|-------------|
88
+ | `--target <path>` | — | Target source file to create or edit |
89
+ | `--models <glob>` | `models/**/*.ts` | Glob pattern for model definition files |
90
+ | `--adapter <name>` | `mock` | LLM adapter: `claude`, `openai`, `gemini`, `cursor`, `mock` |
91
+ | `--model <name>` | — | Model name override for the adapter |
92
+ | `--dry-run` | `false` | Output the prompt without calling the LLM |
93
+ | `--report-format` | `json` | Output format: `json`, `text`, `yaml` |
94
+ | `--output <path>` | — | Write result to file instead of stdout |
95
+ | `--fail-on` | `error` | Minimum severity that causes exit code 10 |
96
+
97
+ ### `litedbmodel-gen audit [target]`
98
+
99
+ Scans TypeScript source files for the eight anti-patterns listed above. Returns structured findings with severity ratings and remediation guidance referencing the correct litedbmodel API.
100
+
101
+ ```bash
102
+ # Audit a directory
103
+ npx litedbmodel-gen audit src/services/ --adapter claude
104
+
105
+ # Audit a single file with strict mode
106
+ npx litedbmodel-gen audit src/services/meal.service.ts \
107
+ --adapter claude --fail-on warning
108
+
109
+ # Output as text
110
+ npx litedbmodel-gen audit src/ --adapter claude --report-format text
111
+ ```
112
+
113
+ | Option | Default | Description |
114
+ |--------|---------|-------------|
115
+ | `--adapter <name>` | `mock` | LLM adapter: `claude`, `openai`, `gemini`, `cursor`, `mock` |
116
+ | `--model <name>` | — | Model name override for the adapter |
117
+ | `--dry-run` | `false` | Output the prompt without calling the LLM |
118
+ | `--report-format` | `json` | Output format: `json`, `text`, `yaml` |
119
+ | `--output <path>` | — | Write result to file instead of stdout |
120
+ | `--fail-on` | `error` | Minimum severity that causes exit code 10 |
121
+
122
+ ### Recommended Workflow
123
+
124
+ ```
125
+ schema.sql ──> embedoc generate + build ──> models/*.ts
126
+ │
127
+ ┌─────────────────────┘
128
+ v
129
+ implement (new feature)
130
+ │
131
+ v
132
+ hand-written code
133
+ │
134
+ v
135
+ audit (verify quality)
136
+ │
137
+ ┌────────┴────────┐
138
+ v v
139
+ clean findings
140
+ │
141
+ v
142
+ fix and re-audit
143
+ ```
144
+
145
+ 1. **Generate models** from `schema.sql` using embedoc
146
+ 2. **Implement** — describe the feature and get code that uses litedbmodel correctly
147
+ 3. **Write** — integrate the generated code into your project
148
+ 4. **Audit** — scan for anti-patterns in the result (or any existing code)
149
+ 5. **Fix and re-audit** until clean
150
+
151
+ ### Exit Codes
152
+
153
+ | Code | Meaning |
154
+ |------|---------|
155
+ | `0` | Success (no findings above `--fail-on` threshold) |
156
+ | `1` | General error |
157
+ | `3` | Input validation failed |
158
+ | `10` | Findings at or above `--fail-on` threshold |
159
+ | `11` | `agent-contracts-runtime` not installed |
160
+ | `12` | Adapter initialization failed (missing API key) |
161
+
162
+ ### Environment Variables
163
+
164
+ | Variable | Adapter |
165
+ |----------|---------|
166
+ | `ANTHROPIC_API_KEY` | `claude` |
167
+ | `OPENAI_API_KEY` | `openai` |
168
+ | `GEMINI_API_KEY` | `gemini` |
169
+ | `CURSOR_API_KEY` | `cursor` |
170
+
171
+ ---
172
+
173
+ ## Code Generation
174
+
175
+ litedbmodel-gen provides two [embedoc](https://www.npmjs.com/package/embedoc) plugins for generating model column definitions from SQL DDL:
176
+
177
+ 1. **Datasource** (`sql_schema`) — reads and parses a `schema.sql` file into structured table definitions
10
178
  2. **Renderer** (`litedbmodel_columns`) — generates `@column()` decorator code from the datasource
11
179
 
12
180
  Using embedoc's in-place marker system, only the column definitions inside markers are auto-updated. Hand-written code (relations, custom methods, exports) outside the markers is preserved.
@@ -32,23 +200,13 @@ export const User = UserModel.asModel();
32
200
  export type User = InstanceType<typeof User>;
33
201
  ```
34
202
 
35
- ## Quick Start
203
+ ### Setup
36
204
 
37
- ### 1. Initialize embedoc in your project
205
+ #### 1. Initialize embedoc and litedbmodel-gen
38
206
 
39
207
  ```bash
40
208
  npx embedoc init
41
- ```
42
-
43
- ### 2. Install litedbmodel-gen
44
-
45
- ```bash
46
209
  npm install -D litedbmodel-gen
47
- ```
48
-
49
- ### 3. Run the init command
50
-
51
- ```bash
52
210
  npx litedbmodel-gen init
53
211
  ```
54
212
 
@@ -65,7 +223,7 @@ If your config file is not at the default `embedoc.config.yaml`:
65
223
  npx litedbmodel-gen init path/to/embedoc.config.yaml
66
224
  ```
67
225
 
68
- ### 4. Edit the config
226
+ #### 2. Edit the config
69
227
 
70
228
  Open `embedoc.config.yaml` and set the schema path and database dialect:
71
229
 
@@ -81,7 +239,7 @@ datasources:
81
239
  overwrite: false
82
240
  ```
83
241
 
84
- ### 5. Generate and build
242
+ #### 3. Generate and build
85
243
 
86
244
  ```bash
87
245
  # Create model files for each table
@@ -94,27 +252,9 @@ npx embedoc build
94
252
  npx embedoc watch
95
253
  ```
96
254
 
97
- ## Workflow
255
+ ### Supported SQL Types
98
256
 
99
- ```
100
- schema.sql changes
101
- |
102
- v
103
- embedoc build / watch
104
- |
105
- +-- existing models/*.ts
106
- | column definitions inside markers are updated
107
- | relations and exports are preserved
108
- |
109
- +-- new tables
110
- embedoc generate --datasource schema
111
- creates new model files from template
112
- embedoc build fills in column definitions
113
- ```
114
-
115
- ## Supported SQL Types
116
-
117
- ### Common (all dialects)
257
+ #### Common (all dialects)
118
258
 
119
259
  | SQL Type | Decorator | TypeScript Type |
120
260
  |----------|-----------|-----------------|
@@ -128,7 +268,7 @@ embedoc build / watch
128
268
  | `JSON`, `JSONB` | `@column.json<Record<string, unknown>>()` | `Record<string, unknown>` |
129
269
  | `UUID` | `@column.uuid()` | `string` |
130
270
 
131
- ### PostgreSQL Arrays
271
+ #### PostgreSQL Arrays
132
272
 
133
273
  | SQL Type | Decorator | TypeScript Type |
134
274
  |----------|-----------|-----------------|
@@ -138,17 +278,17 @@ embedoc build / watch
138
278
  | `BOOLEAN[]` | `@column.booleanArray()` | `(boolean \| null)[]` |
139
279
  | `TIMESTAMP[]` | `@column.datetimeArray()` | `(Date \| null)[]` |
140
280
 
141
- ### MySQL-specific
281
+ #### MySQL-specific
142
282
 
143
283
  | SQL Type | Decorator | TypeScript Type |
144
284
  |----------|-----------|-----------------|
145
285
  | `TINYINT(1)` | `@column.boolean()` | `boolean` |
146
286
 
147
- ### Primary Keys
287
+ #### Primary Keys
148
288
 
149
289
  Columns with `PRIMARY KEY` constraints use `@column({ primaryKey: true })`. For UUID primary keys: `@column.uuid({ primaryKey: true })`. Composite primary keys are supported.
150
290
 
151
- ## Marker Syntax
291
+ ### Marker Syntax
152
292
 
153
293
  Inside your model class:
154
294
 
@@ -164,14 +304,9 @@ If your datasource is not named `schema`, specify it:
164
304
  /*@embedoc:litedbmodel_columns table="users" datasource="my_schema"*/
165
305
  ```
166
306
 
167
- ## CLI
307
+ ## CLI Reference
168
308
 
169
- **[📖 CLI Reference](./docs/cli-reference.md)** | **[📄 CLI Contract](./cli-contract.yaml)**
170
-
171
- ```bash
172
- # Initialize litedbmodel-gen in an embedoc project
173
- npx litedbmodel-gen init [config-path]
174
- ```
309
+ **[Full CLI Reference](./docs/cli-reference.md)** | **[CLI Contract](./cli-contract.yaml)**
175
310
 
176
311
  ## API
177
312
 
@@ -200,6 +335,7 @@ const tables = parseSchema(sql, { database: 'PostgreSQL' });
200
335
 
201
336
  - Node.js 18+
202
337
  - embedoc >= 0.11.0
338
+ - agent-contracts-runtime >= 0.32.0 (for `implement` and `audit` commands)
203
339
 
204
340
  ## License
205
341