prisma-zod-generator 1.2.0 → 1.3.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.
Files changed (78) hide show
  1. package/README.md +1146 -524
  2. package/lib/config/defaults.d.ts +106 -0
  3. package/lib/config/defaults.js +493 -0
  4. package/lib/config/defaults.js.map +1 -0
  5. package/lib/config/errors.d.ts +164 -0
  6. package/lib/config/errors.js +399 -0
  7. package/lib/config/errors.js.map +1 -0
  8. package/lib/config/generator-options.d.ts +93 -0
  9. package/lib/config/generator-options.js +353 -0
  10. package/lib/config/generator-options.js.map +1 -0
  11. package/lib/config/parser.d.ts +139 -0
  12. package/lib/config/parser.js +227 -0
  13. package/lib/config/parser.js.map +1 -0
  14. package/lib/config/schema.d.ts +118 -0
  15. package/lib/config/schema.js +410 -0
  16. package/lib/config/schema.js.map +1 -0
  17. package/lib/config/validator.d.ts +79 -0
  18. package/lib/config/validator.js +357 -0
  19. package/lib/config/validator.js.map +1 -0
  20. package/lib/generators/model.d.ts +526 -0
  21. package/lib/generators/model.js +1719 -0
  22. package/lib/generators/model.js.map +1 -0
  23. package/lib/generators/results.d.ts +157 -0
  24. package/lib/generators/results.js +494 -0
  25. package/lib/generators/results.js.map +1 -0
  26. package/lib/helpers/aggregate-helpers.d.ts +8 -0
  27. package/lib/helpers/aggregate-helpers.js +80 -37
  28. package/lib/helpers/aggregate-helpers.js.map +1 -1
  29. package/lib/helpers/helpers.js +8 -4
  30. package/lib/helpers/helpers.js.map +1 -1
  31. package/lib/helpers/include-helpers.d.ts +4 -0
  32. package/lib/helpers/include-helpers.js +50 -26
  33. package/lib/helpers/include-helpers.js.map +1 -1
  34. package/lib/helpers/index.d.ts +1 -0
  35. package/lib/helpers/index.js +1 -0
  36. package/lib/helpers/index.js.map +1 -1
  37. package/lib/helpers/model-helpers.d.ts +35 -0
  38. package/lib/helpers/model-helpers.js +117 -0
  39. package/lib/helpers/model-helpers.js.map +1 -1
  40. package/lib/helpers/mongodb-helpers.d.ts +4 -0
  41. package/lib/helpers/mongodb-helpers.js +61 -3
  42. package/lib/helpers/mongodb-helpers.js.map +1 -1
  43. package/lib/helpers/select-helpers.js +42 -13
  44. package/lib/helpers/select-helpers.js.map +1 -1
  45. package/lib/helpers/zod-integration.d.ts +104 -0
  46. package/lib/helpers/zod-integration.js +317 -0
  47. package/lib/helpers/zod-integration.js.map +1 -0
  48. package/lib/parsers/zodComments.d.ts +198 -0
  49. package/lib/parsers/zodComments.js +1127 -0
  50. package/lib/parsers/zodComments.js.map +1 -0
  51. package/lib/prisma-generator.js +961 -14
  52. package/lib/prisma-generator.js.map +1 -1
  53. package/lib/transformer.d.ts +200 -1
  54. package/lib/transformer.js +1288 -84
  55. package/lib/transformer.js.map +1 -1
  56. package/lib/types/variants.d.ts +149 -0
  57. package/lib/types/variants.js +99 -0
  58. package/lib/types/variants.js.map +1 -0
  59. package/lib/utils/naming.d.ts +180 -0
  60. package/lib/utils/naming.js +364 -0
  61. package/lib/utils/naming.js.map +1 -0
  62. package/lib/utils/singleFileAggregator.d.ts +4 -0
  63. package/lib/utils/singleFileAggregator.js +165 -0
  64. package/lib/utils/singleFileAggregator.js.map +1 -0
  65. package/lib/utils/writeFileSafely.js +30 -2
  66. package/lib/utils/writeFileSafely.js.map +1 -1
  67. package/lib/utils/writeIndexFile.js +67 -1
  68. package/lib/utils/writeIndexFile.js.map +1 -1
  69. package/lib/variants/config.d.ts +150 -0
  70. package/lib/variants/config.js +439 -0
  71. package/lib/variants/config.js.map +1 -0
  72. package/lib/variants/exports.d.ts +130 -0
  73. package/lib/variants/exports.js +459 -0
  74. package/lib/variants/exports.js.map +1 -0
  75. package/lib/variants/generator.d.ts +135 -0
  76. package/lib/variants/generator.js +456 -0
  77. package/lib/variants/generator.js.map +1 -0
  78. package/package.json +22 -5
package/README.md CHANGED
@@ -23,196 +23,180 @@
23
23
  </p>
24
24
 
25
25
  <p>
26
- <strong>🎯 Zero-config • 🛡️ Type-safe • Fast • 🔧 Customizable</strong>
26
+ <strong>:dart: Zero-config • :shield: Type-safe • :zap: Fast • :wrench: Customizable</strong>
27
27
  </p>
28
28
 
29
29
  </div>
30
30
 
31
31
  ---
32
32
 
33
- <br>
34
-
35
33
  <div align="center">
36
- <h3>💡 Transform your Prisma schema into type-safe validation schemas</h3>
34
+ <h3>:bulb: Transform your Prisma schema into type-safe validation schemas</h3>
37
35
  <p><em>Automatically generates Zod schemas for all Prisma operations with full TypeScript support</em></p>
38
36
  </div>
39
37
 
40
38
  <div align="center">
41
39
 
42
- ## 💖 **Support This Project**
40
+ <a id="sponsor"></a>
41
+ ## :sparkling_heart: Sponsor to Keep This Project Active
43
42
 
44
- <p><em>If this tool accelerates your development, consider supporting its growth</em></p>
43
+ <p><strong>:rotating_light: Active maintenance depends on your sponsorship. If this generator saves you time, please consider sponsoring.</strong></p>
45
44
 
46
45
  <a href="https://github.com/sponsors/omar-dulaimi">
47
46
  <img src="https://img.shields.io/badge/💝_Sponsor_on_GitHub-ea4aaa?style=for-the-badge&logo=github&logoColor=white" alt="GitHub Sponsors" height="45">
48
47
  </a>
49
48
 
50
- <p><strong>✨ Your sponsorship drives innovation and keeps this project thriving ✨</strong></p>
49
+ <p><em>Your support funds maintenance, issue triage, new features, documentation, and community help.</em></p>
51
50
 
52
51
  </div>
53
52
 
53
+ ---
54
54
 
55
- ### ✨ **Core Features**
56
55
 
57
- <div align="center">
58
-
59
- | 🚀 **Feature** | 📦 **Version** | 🎯 **Benefit** |
60
- |----------------|----------------|------------------|
61
- | **New Prisma Client** | `6.12.0+` | 🆕 ESM-compatible generator support |
62
- | **Prisma** | `6.12.0+` | 🏃‍♂️ Latest features & performance |
63
- | **Zod** | `4.0.5+` | 🛡️ Enhanced validation & type safety |
64
- | **TypeScript** | `5.8+` | ⚡ Cutting-edge language features |
65
- | **Testing** | `Vitest 3` | 🧪 Comprehensive coverage |
66
- | **Tooling** | `ESLint 9` | 🔧 Modern dev experience |
67
- | **Multi-DB** | `All Providers` | 🗄️ PostgreSQL, MySQL, MongoDB, SQLite+ |
68
-
69
- </div>
70
56
 
71
- <div align="center">
72
-
73
- ### 📦 **Installation**
74
-
75
- </div>
57
+ ## :clipboard: **Table of Contents**
58
+
59
+ <table>
60
+ <tr>
61
+ <td><a href="#sponsor">:sparkling_heart: Sponsor</a></td>
62
+ <td><a href="#-quick-start">:rocket: Quick Start</a></td>
63
+ <td><a href="#-generated-output">:clipboard: Generated Output</a></td>
64
+ <td><a href="#-version-compatibility">:package: Compatibility</a></td>
65
+ <td><a href="#-core-examples">:books: Core Examples</a></td>
66
+ </tr>
67
+ <tr>
68
+ <td><a href="#-advanced-features">:wrench: Advanced Features</a></td>
69
+ <td><a href="#-configuration">:gear: Configuration</a></td>
70
+ <td><a href="#-api-reference">:book: API Reference</a></td>
71
+ <td><a href="#-framework-examples">:globe_with_meridians: Framework Examples</a></td>
72
+ </tr>
73
+ <td><a href="#-testing--development">:test_tube: Testing & Development</a></td>
74
+ <td><a href="#-troubleshooting">:mag: Troubleshooting</a></td>
75
+ <td><a href="#-contributing">:handshake: Contributing</a></td>
76
+ <td></td>
77
+ </tr>
78
+ </table>
79
+
80
+ ---
81
+
82
+ ## :rocket: Quick Start
83
+
84
+ ### Installation
76
85
 
77
86
  ```bash
78
- # 🚀 Install the latest release
87
+ # NPM
79
88
  npm install prisma-zod-generator
89
+
90
+ # Yarn
91
+ yarn add prisma-zod-generator
92
+
93
+ # PNPM
94
+ pnpm add prisma-zod-generator
80
95
  ```
81
96
 
82
- ### 🔄 Upgrading
97
+ ### 2. Add generator block to your Prisma schema
83
98
 
84
- The latest stable version maintains full API compatibility. Requirements:
85
- - **Node.js 18+**
86
- - **Prisma 6.12.0+**
87
- - **Zod 4.0.5+**
99
+ Add the Prisma Zod Generator to your `schema.prisma` with inline options. You can also supply a JSON config via `config` for advanced/nested settings.
88
100
 
89
- Simply update your dependencies and re-run `npx prisma generate` - no code changes needed!
101
+ ```prisma
102
+ generator zod {
103
+ provider = "prisma-zod-generator" // required: package id
104
+ output = "./generated" // required: where to write output
105
+
106
+ // File output mode
107
+ useMultipleFiles = true // true: multi-file (default), false: single-file bundle
108
+ singleFileName = "schemas.ts" // only when useMultipleFiles=false
109
+ placeSingleFileAtRoot = true // single-file at output root (true) or under schemas/ (false)
110
+
111
+ // Legacy select/include flags (override JSON config if both provided)
112
+ isGenerateSelect = false
113
+ isGenerateInclude = false
114
+
115
+ // Optional: external JSON config for nested options (models, variants, exclusions, etc.)
116
+ // When both sources specify the same simple option, this generator block wins.
117
+ config = "./zod-generator.config.json"
118
+ }
119
+ ```
120
+
121
+ ### 3. Configure TypeScript (required)
122
+
123
+ ```json
124
+ {
125
+ "compilerOptions": {
126
+ "strict": true
127
+ }
128
+ }
129
+ ```
130
+
131
+ ### 4. Generate schemas
90
132
 
91
133
  ```bash
92
- npm update prisma-zod-generator
93
134
  npx prisma generate
94
135
  ```
95
136
 
96
- <div align="center">
97
-
98
- ## 📚 **Navigation**
99
-
100
- <table>
101
- <tr>
102
- <td><a href="#-features">✨ Features</a></td>
103
- <td><a href="#-quick-start">🚀 Quick Start</a></td>
104
- <td><a href="#-generated-output">📋 Output</a></td>
105
- <td><a href="#️-configuration-options">⚙️ Config</a></td>
106
- </tr>
107
- <tr>
108
- <td><a href="#-advanced-usage">🔧 Advanced</a></td>
109
- <td><a href="#-examples">📚 Examples</a></td>
110
- <td><a href="#-troubleshooting">🔍 Troubleshooting</a></td>
111
- <td><a href="#-contributing">🤝 Contributing</a></td>
112
- </tr>
113
- </table>
114
-
115
- </div>
137
+ ---
116
138
 
117
- <div align="center">
118
-
119
- ## ✨ **Why Choose Prisma Zod Generator?**
120
-
121
- </div>
139
+ ## ✨ Why Choose Prisma Zod Generator?
122
140
 
123
141
  <table>
124
142
  <tr>
125
143
  <td align="center" width="25%">
126
- <img src="https://img.shields.io/badge/🚀-Zero_Config-blue?style=for-the-badge" alt="Zero Config">
127
- <br><strong>Works instantly</strong><br><em>Sensible defaults included</em>
144
+ <img src="https://img.shields.io/badge/🚀-Zero_Config-blue?style=for-the-badge" alt="Zero Config"><br>
145
+ <strong>Works instantly</strong><br><em>Sensible defaults included</em>
128
146
  </td>
129
147
  <td align="center" width="25%">
130
- <img src="https://img.shields.io/badge/🔄-Auto_Generated-green?style=for-the-badge" alt="Auto Generated">
131
- <br><strong>Always in sync</strong><br><em>Updates with schema changes</em>
148
+ <img src="https://img.shields.io/badge/🔄-Auto_Generated-green?style=for-the-badge" alt="Auto Generated"><br>
149
+ <strong>Always in sync</strong><br><em>Updates with schema changes</em>
132
150
  </td>
133
151
  <td align="center" width="25%">
134
- <img src="https://img.shields.io/badge/🛡️-Type_Safe-purple?style=for-the-badge" alt="Type Safe">
135
- <br><strong>100% TypeScript</strong><br><em>Catch errors at compile time</em>
152
+ <img src="https://img.shields.io/badge/🛡️-Type_Safe-purple?style=for-the-badge" alt="Type Safe"><br>
153
+ <strong>100% TypeScript</strong><br><em>Catch errors at compile time</em>
136
154
  </td>
137
155
  <td align="center" width="25%">
138
- <img src="https://img.shields.io/badge/🎯-Comprehensive-orange?style=for-the-badge" alt="Comprehensive">
139
- <br><strong>Full CRUD coverage</strong><br><em>All Prisma operations included</em>
156
+ <img src="https://img.shields.io/badge/🎯-Comprehensive-orange?style=for-the-badge" alt="Comprehensive"><br>
157
+ <strong>Full CRUD coverage</strong><br><em>All Prisma operations included</em>
140
158
  </td>
141
159
  </tr>
142
160
  <tr>
143
161
  <td align="center">
144
- <img src="https://img.shields.io/badge/⚙️-Configurable-red?style=for-the-badge" alt="Configurable">
145
- <br><strong>Highly customizable</strong><br><em>Adapt to your needs</em>
162
+ <img src="https://img.shields.io/badge/⚙️-Configurable-red?style=for-the-badge" alt="Configurable"><br>
163
+ <strong>Highly customizable</strong><br><em>Adapt to your needs</em>
146
164
  </td>
147
165
  <td align="center">
148
- <img src="https://img.shields.io/badge/📦-Lightweight-yellow?style=for-the-badge" alt="Lightweight">
149
- <br><strong>Minimal footprint</strong><br><em>Fast generation & runtime</em>
166
+ <img src="https://img.shields.io/badge/📦-Lightweight-yellow?style=for-the-badge" alt="Lightweight"><br>
167
+ <strong>Minimal footprint</strong><br><em>Fast generation & runtime</em>
150
168
  </td>
151
169
  <td align="center">
152
- <img src="https://img.shields.io/badge/🗄️-Multi_DB-cyan?style=for-the-badge" alt="Multi Database">
153
- <br><strong>All databases</strong><br><em>PostgreSQL, MySQL, MongoDB+</em>
170
+ <img src="https://img.shields.io/badge/🗄️-Multi_DB-cyan?style=for-the-badge" alt="Multi Database"><br>
171
+ <strong>All databases</strong><br><em>PostgreSQL, MySQL, MongoDB+</em>
154
172
  </td>
155
173
  <td align="center">
156
- <img src="https://img.shields.io/badge/🎨-Flexible-pink?style=for-the-badge" alt="Flexible">
157
- <br><strong>Your way</strong><br><em>Custom paths & options</em>
174
+ <img src="https://img.shields.io/badge/🎨-Flexible-pink?style=for-the-badge" alt="Flexible"><br>
175
+ <strong>Your way</strong><br><em>Custom paths & options</em>
158
176
  </td>
159
177
  </tr>
160
178
  </table>
161
179
 
162
- ## 🚀 Quick Start
163
-
164
- ### Installation
165
-
166
- ```bash
167
- # NPM
168
- npm install prisma-zod-generator
169
-
170
- # Yarn
171
- yarn add prisma-zod-generator
172
-
173
- # PNPM
174
- pnpm add prisma-zod-generator
175
- ```
176
-
177
- ### Setup
178
-
179
- 1. **Star this repo** 😉
180
-
181
- 2. **Add the generator to your Prisma schema:**
182
-
183
- ```prisma
184
- generator zod {
185
- provider = "prisma-zod-generator"
186
- output = "./generated/schemas" // default: "./generated"
187
- isGenerateSelect = false // default: false
188
- isGenerateInclude = false // default: false
189
- exportTypedSchemas = true // default: true
190
- exportZodSchemas = true // default: true
191
- typedSchemaSuffix = "Schema" // default: "Schema"
192
- zodSchemaSuffix = "ZodSchema" // default: "ZodSchema"
193
- }
194
- ```
195
-
196
- 3. **Enable strict mode in `tsconfig.json`** (required by Zod):
180
+ ### 🔄 Upgrading
197
181
 
198
- ```json
199
- {
200
- "compilerOptions": {
201
- "strict": true,
202
- }
203
- }
204
- ```
182
+ The latest stable version maintains full API compatibility. Requirements:
183
+ - Node.js 18+
184
+ - Prisma 6.12.0+
185
+ - Zod 4.0.5+
205
186
 
206
- 4. **Generate your Zod schemas:**
187
+ Update and regenerate:
207
188
 
208
189
  ```bash
190
+ npm update prisma-zod-generator
209
191
  npx prisma generate
210
192
  ```
211
193
 
212
-
213
194
  ## 📋 Generated Output
214
195
 
215
- For the following schema:
196
+ <details>
197
+ <summary><strong>📁 File Structure Overview</strong></summary>
198
+
199
+ For this Prisma schema:
216
200
 
217
201
  ```prisma
218
202
  model User {
@@ -224,15 +208,10 @@ model User {
224
208
 
225
209
  model Post {
226
210
  id Int @id @default(autoincrement())
227
- createdAt DateTime @default(now())
228
- updatedAt DateTime @updatedAt
229
211
  title String
230
212
  content String?
231
- published Boolean @default(false)
232
- viewCount Int @default(0)
233
213
  author User? @relation(fields: [authorId], references: [id])
234
214
  authorId Int?
235
- likes BigInt
236
215
  }
237
216
  ```
238
217
 
@@ -252,322 +231,189 @@ The generator creates:
252
231
  └── 📄 index.ts # Barrel exports
253
232
  ```
254
233
 
255
- ## 🚀 Dual Schema Export Strategy - Breakthrough Feature!
234
+ </details>
235
+
236
+ ---
237
+
238
+ ## :rocket: Dual Schema Export Strategy - Breakthrough Feature!
256
239
 
257
- ### 🎯 **Solving the Type Safety vs Method Availability Trade-off**
240
+ ### 🎯 Solving the Type Safety vs Method Availability Trade-off
258
241
 
259
- This generator implements a **revolutionary dual export strategy** that solves a fundamental limitation in TypeScript + Zod integration!
242
+ This generator implements a dual export strategy that gives you both perfect Prisma typing and full Zod method support.
260
243
 
261
244
  #### The Problem
262
245
  With Zod schemas, you traditionally face a choice:
263
- - **Type-Safe**: `z.ZodType<Prisma.Type>` gives perfect inference but breaks Zod methods (`.extend()`, `.omit()`, `.merge()`)
264
- - **Method-Friendly**: Pure Zod schemas support all methods but lose perfect type binding
246
+ - Type-safe: `z.ZodType<Prisma.Type>` gives perfect inference but restricts Zod method chaining
247
+ - Method-friendly: Pure Zod schemas support all methods but lose perfect type binding
265
248
 
266
- #### Our Solution: **Export Both Versions!**
249
+ #### Our Solution: Export Both Versions
267
250
 
268
- ```typescript
269
- // Perfect type safety (no methods)
251
+ ```ts
252
+ // Perfect type safety (no Zod method chaining)
270
253
  export const PostFindManySchema: z.ZodType<Prisma.PostFindManyArgs> = schema;
271
254
 
272
- // Full method availability (good inference)
255
+ // Full method availability (great inference)
273
256
  export const PostFindManyZodSchema = schema;
274
257
  ```
275
258
 
276
259
  #### Usage Examples
277
260
 
278
- **🔒 Type-Safe Version** (Perfect Prisma integration):
279
- ```typescript
261
+ Type-safe version (perfect Prisma integration):
262
+
263
+ ```ts
280
264
  import { PostFindManySchema } from './generated/schemas/findManyPost.schema';
281
265
 
282
- // Perfect type inference
283
266
  type FindManyArgs = z.infer<typeof PostFindManySchema>; // Prisma.PostFindManyArgs
284
267
 
285
- // Runtime validation
286
268
  const validatedInput = PostFindManySchema.parse(queryParams);
287
- const posts = await prisma.post.findMany(validatedInput); // ✅ Perfect type safety
269
+ const posts = await prisma.post.findMany(validatedInput);
288
270
  ```
289
271
 
290
- **🔧 Method-Friendly Version** (Full Zod capabilities):
291
- ```typescript
272
+ Method-friendly version (full Zod capabilities):
273
+
274
+ ```ts
292
275
  import { PostFindManyZodSchema } from './generated/schemas/findManyPost.schema';
293
276
 
294
- // All Zod methods work perfectly!
295
277
  const customSchema = PostFindManyZodSchema
296
- .extend({ customField: z.string() }) // ✅ Works!
297
- .omit({ take: true }) // ✅ Works!
298
- .merge(otherSchema); // ✅ Works!
278
+ .extend({ customField: z.string() })
279
+ .omit({ take: true })
280
+ .merge(otherSchema);
299
281
 
300
- const partialSchema = PostFindManyZodSchema.partial(); // ✅ Works!
282
+ const partialSchema = PostFindManyZodSchema.partial();
301
283
  ```
302
284
 
303
285
  #### Configuration Options
304
286
 
305
- Configure dual exports to match your needs:
306
-
307
287
  ```prisma
308
288
  generator zod {
309
- provider = "prisma-zod-generator"
310
- output = "./generated/schemas"
311
-
312
- // Dual export configuration
313
- exportTypedSchemas = true # Export z.ZodType<Prisma.Type> versions
314
- exportZodSchemas = true # Export pure Zod versions
315
- typedSchemaSuffix = "Schema" # Suffix for typed versions
316
- zodSchemaSuffix = "ZodSchema" # Suffix for method-friendly versions
289
+ provider = "prisma-zod-generator"
290
+ output = "./generated/schemas"
291
+ exportTypedSchemas = true // Export z.ZodType<Prisma.Type> versions
292
+ exportZodSchemas = true // Export pure Zod versions
293
+ typedSchemaSuffix = "Schema" // Suffix for typed versions
294
+ zodSchemaSuffix = "ZodSchema" // Suffix for method-friendly versions
317
295
  }
318
296
  ```
319
297
 
320
- #### Generated Schema Examples
321
-
322
- **For `PostFindManySchema`**:
323
- ```typescript
324
- // Type-safe version (perfect inference, no methods)
325
- export const PostFindManySchema: z.ZodType<Prisma.PostFindManyArgs> = z.object({
326
- select: PostSelectSchema.optional(),
327
- where: PostWhereInputObjectSchema.optional(),
328
- take: z.number().optional(),
329
- // ...
330
- }).strict();
331
-
332
- // Method-friendly version (full methods, good inference)
333
- export const PostFindManyZodSchema = z.object({
334
- select: PostSelectSchema.optional(),
335
- where: PostWhereInputObjectSchema.optional(),
336
- take: z.number().optional(),
337
- // ...
338
- }).strict();
339
- ```
340
-
341
- **For inlined Select schemas**:
342
- ```typescript
343
- // Type-safe select schema
344
- export const PostSelectSchema: z.ZodType<Prisma.PostSelect> = z.object({
345
- id: z.boolean().optional(),
346
- title: z.boolean().optional(),
347
- author: z.union([z.boolean(), z.lazy(() => UserArgsObjectSchema)]).optional(),
348
- }).strict();
349
-
350
- // Method-friendly select schema
351
- export const PostSelectZodSchema = z.object({
352
- id: z.boolean().optional(),
353
- title: z.boolean().optional(),
354
- author: z.union([z.boolean(), z.lazy(() => UserArgsObjectSchema)]).optional(),
355
- }).strict();
356
- ```
357
-
358
- #### When to Use Which Version
359
-
360
- | Use Case | Recommended Version | Why |
361
- |----------|-------------------|-----|
362
- | **API Validation** | `PostFindManySchema` | Perfect type safety with Prisma |
363
- | **Schema Composition** | `PostFindManyZodSchema` | Need `.extend()`, `.omit()`, `.merge()` |
364
- | **Runtime Validation** | Either | Identical runtime behavior |
365
- | **Type Inference** | Either | Both provide excellent IntelliSense |
366
-
367
- #### Competitive Advantage
368
-
369
- This breakthrough solves what other generators describe as an **unsolvable trade-off**:
370
-
371
- - ✅ **Perfect Type Safety**: Full Prisma type integration
372
- - ✅ **Full Method Support**: All Zod methods available
373
- - ✅ **Zero Runtime Overhead**: Both versions are identical at runtime
374
- - ✅ **Developer Choice**: Pick the right tool for each use case
375
- - ✅ **Future Proof**: Configurable for different preferences
376
-
377
- **You get BOTH worlds - no compromises!** 🎉
378
-
379
- ### 🎓 **How to Choose Your Configuration**
380
-
381
- The dual export system gives you complete control. Here are common configurations and when to use them:
298
+ #### Configuration Scenarios
382
299
 
383
- #### 📋 **Configuration Scenarios**
300
+ Type-safe only:
384
301
 
385
- **🔒 Type-Safe Only** (Perfect Prisma Integration):
386
302
  ```prisma
387
303
  generator zod {
388
304
  provider = "prisma-zod-generator"
389
- exportTypedSchemas = true # Keep type-safe versions
390
- exportZodSchemas = false # Skip method-friendly versions
305
+ exportTypedSchemas = true
306
+ exportZodSchemas = false
391
307
  }
392
308
  ```
393
- **Best for:** API validation, runtime type checking, perfect Prisma integration
394
- **You get:** `PostFindManySchema: z.ZodType<Prisma.PostFindManyArgs>`
395
309
 
396
- **🔧 Method-Friendly Only** (Full Zod Capabilities):
310
+ Method-friendly only:
311
+
397
312
  ```prisma
398
313
  generator zod {
399
- provider = "prisma-zod-generator"
400
- exportTypedSchemas = false # Skip type-safe versions
401
- exportZodSchemas = true # Keep method-friendly versions
314
+ provider = "prisma-zod-generator"
315
+ exportTypedSchemas = false
316
+ exportZodSchemas = true
402
317
  }
403
318
  ```
404
- **Best for:** Schema composition, form validation, custom transformations
405
- **You get:** `PostFindManyZodSchema` (supports `.extend()`, `.omit()`, `.merge()`)
406
319
 
407
- **🎯 Both Versions** (Maximum Flexibility):
320
+ Both versions:
321
+
408
322
  ```prisma
409
323
  generator zod {
410
324
  provider = "prisma-zod-generator"
411
- exportTypedSchemas = true # Include type-safe versions
412
- exportZodSchemas = true # Include method-friendly versions
325
+ exportTypedSchemas = true
326
+ exportZodSchemas = true
413
327
  }
414
328
  ```
415
- **Best for:** Teams with mixed use cases, gradual migration, maximum flexibility
416
- **You get:** Both `PostFindManySchema` AND `PostFindManyZodSchema`
417
329
 
418
- **🎨 Custom Naming** (Your Preferred Style):
330
+ Custom naming:
331
+
419
332
  ```prisma
420
333
  generator zod {
421
334
  provider = "prisma-zod-generator"
422
335
  exportTypedSchemas = true
423
336
  exportZodSchemas = true
424
- typedSchemaSuffix = "Args" # PostFindManyArgs
425
- zodSchemaSuffix = "Validator" # PostFindManyValidator
337
+ typedSchemaSuffix = "Args"
338
+ zodSchemaSuffix = "Validator"
426
339
  }
427
340
  ```
428
341
 
429
- #### 🚀 **Quick Migration Guide**
342
+ Pro tips:
430
343
 
431
- **From Other Generators:**
432
- 1. Start with `exportTypedSchemas = true, exportZodSchemas = false`
433
- 2. Test your existing API validation code - should work perfectly
434
- 3. Optionally enable `exportZodSchemas = true` for new schema composition needs
344
+ - Smaller bundles: use a single export mode
345
+ - Team consistency: choose one naming convention and stick with it
346
+ - Gradual adoption: start with type-safe schemas, add method-friendly as needed
347
+ - IDE performance: fewer exports -> faster IntelliSense in huge projects
435
348
 
436
- **New Projects:**
437
- - Use **Type-Safe Only** for API endpoints and data validation
438
- - Use **Both Versions** if you need schema composition AND perfect typing
439
- - Use **Method-Friendly Only** for form validation and schema transformations
349
+ ---
440
350
 
441
- #### 💡 **Pro Tips**
351
+ ## :package: Version Compatibility
442
352
 
443
- - **Smaller bundles**: Use single export mode (`exportZodSchemas = false` OR `exportTypedSchemas = false`)
444
- - **Team consistency**: Choose one naming convention and stick with it
445
- - **Gradual adoption**: Start with type-safe schemas, add method-friendly as needed
446
- - **IDE performance**: Fewer exports = faster IntelliSense in large projects
353
+ <details>
354
+ <summary><strong>🔄 Supported Versions & Migration Guide</strong></summary>
447
355
 
448
- ## ⚙️ Configuration Options
356
+ ### Current Requirements
449
357
 
450
- | Option | Description | Type | Default |
451
- |--------|-------------|------|---------|
452
- | `output` | Output directory for generated files | `string` | `"./generated"` |
453
- | `isGenerateSelect` | Generate Select-related schemas | `boolean` | `false` |
454
- | `isGenerateInclude` | Generate Include-related schemas | `boolean` | `false` |
455
- | `exportTypedSchemas` | Export z.ZodType versions (type-safe) | `boolean` | `true` |
456
- | `exportZodSchemas` | Export pure Zod versions (method-friendly) | `boolean` | `true` |
457
- | `typedSchemaSuffix` | Suffix for typed schemas | `string` | `"Schema"` |
458
- | `zodSchemaSuffix` | Suffix for Zod schemas | `string` | `"ZodSchema"` |
358
+ | Component | Version | Status |
359
+ |-----------|---------|---------|
360
+ | **Node.js** | 18+ | Required |
361
+ | **Prisma** | 6.12.0+ | Recommended |
362
+ | **Zod** | 4.0.5+ | Required |
363
+ | **TypeScript** | 5.8+ | Recommended |
459
364
 
460
- ### Example Configuration
365
+ ### Prisma Client Generator Support
461
366
 
367
+ Both legacy and new ESM-compatible generators are supported:
368
+
369
+ #### Legacy Generator (Existing Projects)
462
370
  ```prisma
463
- generator zod {
464
- provider = "prisma-zod-generator"
465
- output = "./src/schemas"
466
- isGenerateSelect = true
467
- isGenerateInclude = true
371
+ generator client {
372
+ provider = "prisma-client-js"
468
373
  }
469
374
  ```
470
375
 
471
- ## 🔧 Advanced Usage
472
-
473
- ### Model Customizations
474
-
475
- Hide specific models from generation:
476
-
376
+ #### New ESM Generator (Prisma 6.12.0+)
477
377
  ```prisma
478
- /// @@Gen.model(hide: true)
479
- model InternalLog {
480
- id Int @id @default(autoincrement())
481
- message String
482
- createdAt DateTime @default(now())
378
+ generator client {
379
+ provider = "prisma-client"
380
+ output = "./src/generated/client"
381
+ runtime = "nodejs"
382
+ moduleFormat = "esm"
383
+ generatedFileExtension = "ts"
384
+ importFileExtension = "ts"
483
385
  }
484
386
  ```
485
387
 
486
- ### Database Provider Support
487
-
488
- The generator supports all Prisma database providers:
489
-
490
- - **PostgreSQL** - Complete support including advanced types
491
- - **MySQL** - Full compatibility with all MySQL features
492
- - **MongoDB** - Native MongoDB schema generation
493
- - **SQLite** - Perfect for development and testing
494
- - **SQL Server** - Enterprise-grade support
495
- - **CockroachDB** - Distributed database support
388
+ ### Migration Guide
496
389
 
497
- ## 📚 Examples
390
+ **Existing Projects**: No changes needed - continue using `prisma-client-js`
498
391
 
499
- ### Express.js API Validation
392
+ **New Projects**: Consider the new `prisma-client` generator for ESM support
500
393
 
501
- ```typescript
502
- import express from 'express';
503
- import { PostCreateOneSchema, UserFindManySchema } from './generated/schemas';
394
+ </details>
504
395
 
505
- const app = express();
396
+ ---
506
397
 
507
- // Create post with validation
508
- app.post('/posts', async (req, res) => {
509
- try {
510
- const data = PostCreateOneSchema.parse(req.body);
511
- const post = await prisma.post.create(data);
512
- res.json(post);
513
- } catch (error) {
514
- if (error instanceof z.ZodError) {
515
- return res.status(400).json({ errors: error.errors });
516
- }
517
- res.status(500).json({ error: 'Internal server error' });
518
- }
519
- });
398
+ ## 📚 Core Examples
520
399
 
521
- // Query with validation
522
- app.get('/users', async (req, res) => {
523
- const query = UserFindManySchema.parse(req.query);
524
- const users = await prisma.user.findMany(query);
525
- res.json(users);
526
- });
527
- ```
400
+ <details>
401
+ <summary><strong>🎯 Essential Usage Patterns</strong></summary>
528
402
 
529
- ### Next.js API Routes
403
+ ### API Validation
530
404
 
531
405
  ```typescript
532
- // pages/api/users.ts
533
- import type { NextApiRequest, NextApiResponse } from 'next';
534
- import { UserCreateOneSchema } from '../../generated/schemas';
535
-
536
- export default async function handler(req: NextApiRequest, res: NextApiResponse) {
537
- if (req.method === 'POST') {
538
- try {
539
- const userData = UserCreateOneSchema.parse(req.body);
540
- const user = await prisma.user.create(userData);
541
- res.status(201).json(user);
542
- } catch (error) {
543
- res.status(400).json({ error: error.message });
544
- }
545
- }
546
- }
547
- ```
548
-
549
- ### tRPC Integration
406
+ // Validate input data
407
+ const createUser = UserCreateInputObjectSchema.parse(requestData);
550
408
 
551
- ```typescript
552
- import { z } from 'zod';
553
- import { PostCreateOneSchema, PostFindManySchema } from './generated/schemas';
409
+ // Validate query parameters
410
+ const findUsers = UserFindManySchema.parse(queryParams);
554
411
 
555
- export const postRouter = router({
556
- create: publicProcedure
557
- .input(PostCreateOneSchema)
558
- .mutation(({ input }) => {
559
- return prisma.post.create(input);
560
- }),
561
-
562
- list: publicProcedure
563
- .input(PostFindManySchema)
564
- .query(({ input }) => {
565
- return prisma.post.findMany(input);
566
- }),
567
- });
412
+ // Validate update operations
413
+ const updateUser = UserUpdateOneSchema.parse(updateData);
568
414
  ```
569
415
 
570
- ### React Hook Form Integration
416
+ ### Form Validation with React Hook Form
571
417
 
572
418
  ```typescript
573
419
  import { useForm } from 'react-hook-form';
@@ -579,243 +425,1036 @@ function CreateUserForm() {
579
425
  resolver: zodResolver(UserCreateInputObjectSchema)
580
426
  });
581
427
 
582
- const onSubmit = async (data) => {
583
- const response = await fetch('/api/users', {
584
- method: 'POST',
585
- headers: { 'Content-Type': 'application/json' },
586
- body: JSON.stringify({ data })
587
- });
588
- };
589
-
590
428
  return (
591
429
  <form onSubmit={handleSubmit(onSubmit)}>
592
430
  <input {...register('email')} type="email" />
593
431
  {errors.email && <span>{errors.email.message}</span>}
594
-
595
- <input {...register('name')} />
596
- {errors.name && <span>{errors.name.message}</span>}
597
-
598
432
  <button type="submit">Create User</button>
599
433
  </form>
600
434
  );
601
435
  }
602
436
  ```
603
437
 
604
- ## 🔧 API Reference
605
-
606
- ### Generated Schema Types
607
-
608
- The generator creates the following types of schemas:
609
-
610
- #### Operation Schemas
611
- - **Create Operations**: `ModelCreateOneSchema`, `ModelCreateManySchema`
612
- - **Read Operations**: `ModelFindManySchema`, `ModelFindUniqueSchema`, `ModelFindFirstSchema`
613
- - **Update Operations**: `ModelUpdateOneSchema`, `ModelUpdateManySchema`, `ModelUpsertSchema`
614
- - **Delete Operations**: `ModelDeleteOneSchema`, `ModelDeleteManySchema`
615
- - **Aggregate Operations**: `ModelAggregateSchema`, `ModelGroupBySchema`
438
+ ### Database Operations
616
439
 
617
- #### Input Object Schemas
618
- - **Create Inputs**: `ModelCreateInputObjectSchema`, `ModelCreateNestedInputObjectSchema`
619
- - **Update Inputs**: `ModelUpdateInputObjectSchema`, `ModelUpdateNestedInputObjectSchema`
620
- - **Where Inputs**: `ModelWhereInputObjectSchema`, `ModelWhereUniqueInputObjectSchema`
621
- - **Order Inputs**: `ModelOrderByInputObjectSchema`
440
+ ```typescript
441
+ // Safe database queries with validation
442
+ const searchUsers = async (params: unknown) => {
443
+ const validatedParams = UserFindManySchema.parse(params);
444
+ return await prisma.user.findMany(validatedParams);
445
+ };
446
+
447
+ // Validated mutations
448
+ const createPost = async (data: unknown) => {
449
+ const validatedData = PostCreateOneSchema.parse(data);
450
+ return await prisma.post.create(validatedData);
451
+ };
452
+ ```
622
453
 
623
- #### Select & Include Schemas (Optional)
624
- When enabled with `isGenerateSelect: true` and `isGenerateInclude: true`:
625
- - **Select Schemas**: `ModelSelectObjectSchema`
626
- - **Include Schemas**: `ModelIncludeObjectSchema`
454
+ </details>
627
455
 
628
- ### Schema Naming Convention
456
+ ---
629
457
 
630
- All generated schemas follow a consistent naming pattern:
631
- ```
632
- {ModelName}{Operation}{Type}Schema
633
- ```
458
+ ## 🔧 Advanced Features
634
459
 
635
- Examples:
636
- - `UserCreateOneSchema` - Schema for creating a single user
637
- - `PostFindManyArgsSchema` - Schema for finding multiple posts with arguments
638
- - `UserWhereInputObjectSchema` - Schema for user where conditions
460
+ <details>
461
+ <summary><strong>🎯 Configuration System</strong></summary>
639
462
 
640
- ## 🔍 Troubleshooting
463
+ Looking for ready-made configs? See the new Recipes catalog in `recipes/` for common setups (single file, models-only, minimal CRUD, tRPC, API result schemas, hide fields, and more).
641
464
 
642
- ### Latest Version Information
465
+ ### JSON-Based Configuration
643
466
 
644
- **Recent Schema Compilation Fixes**
645
- - **SortOrderInput schemas**: Fixed unnecessary lazy loading that caused validation issues
646
- - **Args schemas**: Resolved TypeScript compilation errors for UserArgs, ProfileArgs, etc.
647
- - **All schemas**: Now compile cleanly without type constraint issues
648
- - **Full backward compatibility**: No code changes needed when upgrading
467
+ Create `zod-generator.config.json`:
649
468
 
650
- **Generator Support**
651
- - Both `prisma-client-js` and `prisma-client` generators are fully supported
652
- - If using the new generator, ensure Prisma 6.12.0+ is installed
653
- - Clear error messages guide you if no compatible generator is found
469
+ ```json
470
+ {
471
+ "mode": "custom",
472
+ "output": "./src/generated/zod",
473
+ "globalExclusions": {
474
+ "input": ["id", "createdAt", "updatedAt"],
475
+ "result": [],
476
+ "pure": ["password", "hashedPassword"]
477
+ },
478
+ "variants": {
479
+ "pure": {
480
+ "enabled": true,
481
+ "suffix": ".model",
482
+ "excludeFields": []
483
+ },
484
+ "input": {
485
+ "enabled": true,
486
+ "suffix": ".input",
487
+ "excludeFields": ["id"]
488
+ },
489
+ "result": {
490
+ "enabled": true,
491
+ "suffix": ".result",
492
+ "excludeFields": ["password"]
493
+ }
494
+ },
495
+ "models": {
496
+ "User": {
497
+ "enabled": true,
498
+ "operations": ["findMany", "findUnique", "create", "update"],
499
+ "variants": {
500
+ "input": {
501
+ "excludeFields": ["role", "permissions"]
502
+ }
503
+ }
504
+ }
505
+ }
506
+ }
507
+ ```
654
508
 
655
- **Current Requirements**
656
- - Requires Node.js 18+
657
- - Requires Prisma 6.12.0+ and Zod 4.0.5+
658
- - All peer dependencies must be compatible
509
+ ### Configuration Modes
659
510
 
660
- **Upgrading to Latest Version**
661
- - Backup your project before upgrading
662
- - Update all related dependencies (Prisma, Zod, TypeScript)
663
- - Re-run `npx prisma generate` after upgrading
664
- - Test thoroughly in development environment
511
+ ```typescript
512
+ // Minimal mode - essential operations only
513
+ const minimalConfig = {
514
+ mode: "minimal",
515
+ operations: ["findMany", "findUnique", "create", "update"]
516
+ };
517
+
518
+ // Full mode - all operations and features
519
+ const fullConfig = {
520
+ mode: "full",
521
+ includeAggregations: true,
522
+ includeGroupBy: true
523
+ };
524
+ ```
665
525
 
666
- ### Common Issues
526
+ </details>
667
527
 
668
- **Generator compatibility errors**
669
- - Ensure you have either `prisma-client-js` or `prisma-client` generator in your schema
670
- - The Zod generator provides clear error messages with examples if no compatible generator is found
671
- - Both legacy and new generators are supported simultaneously
528
+ <details>
529
+ <summary><strong>🎨 Schema Variants</strong></summary>
672
530
 
673
- **Error: Cannot find module './generated/schemas'**
674
- - Ensure you've run `npx prisma generate` after adding the generator
675
- - Check that your output path is correct
531
+ ### Multiple Schema Types
676
532
 
677
- **TypeScript errors in generated schemas**
678
- - Make sure all dependencies are installed and up to date
679
- - Ensure `strict: true` is enabled in `tsconfig.json`
533
+ Generate different schema variants for various use cases:
680
534
 
681
- **Generated schemas not updating**
682
- - Run `npx prisma generate` after modifying your schema
683
- - Check that the generator is properly configured in `schema.prisma`
684
- - Clear your build cache and regenerate
535
+ ```typescript
536
+ // Pure model schemas - exact Prisma model structure
537
+ import { UserModelSchema } from './schemas/User.model';
685
538
 
686
- **Zod validation errors**
687
- - Ensure you have Zod 4.0.5+ installed for compatibility
688
- - Check that your input schemas match your Prisma model types
539
+ // Input schemas - for API endpoints and forms
540
+ import { UserInputSchema } from './schemas/User.input';
689
541
 
690
- **Generator fails to run**
691
- - Ensure you have the correct version installed
692
- - Check that your `schema.prisma` syntax is valid
693
- - Verify Node.js version compatibility (18+)
694
- - Clear node_modules and reinstall dependencies
542
+ // Result schemas - for API responses
543
+ import { UserResultSchema } from './schemas/User.result';
695
544
 
696
- ### Performance Considerations
545
+ // Usage examples
546
+ const createUser = UserInputSchema.parse(formData);
547
+ const userResponse = UserResultSchema.parse(dbResult);
548
+ const pureUser = UserModelSchema.parse(prismaModel);
549
+ ```
697
550
 
698
- #### Large Schemas
699
- For projects with many models (50+), consider:
700
- - Using selective generation with model hiding
701
- - Splitting schemas into multiple files
702
- - Implementing lazy loading for schemas
551
+ ### Variant Configuration
703
552
 
704
- #### Build Times
705
- To optimize build performance:
706
- - Add generated files to `.gitignore`
707
- - Use parallel builds where possible
708
- - Consider caching in CI/CD pipelines
553
+ ```json
554
+ {
555
+ "variants": [
556
+ {
557
+ "name": "input",
558
+ "suffix": "Input",
559
+ "exclude": ["id", "createdAt", "updatedAt"]
560
+ },
561
+ {
562
+ "name": "result",
563
+ "suffix": "Result",
564
+ "exclude": ["password"]
565
+ },
566
+ {
567
+ "name": "public",
568
+ "suffix": "Public",
569
+ "exclude": ["password", "email", "internalId"]
570
+ }
571
+ ]
572
+ }
573
+ ```
709
574
 
710
- ### FAQ
575
+ </details>
711
576
 
712
- **Q: Can I customize the generated schema validation rules?**
713
- A: The schemas are generated based on your Prisma schema constraints. Modify your Prisma model definitions to change validation rules.
577
+ <details>
578
+ <summary><strong>🔍 Field Exclusion System</strong></summary>
714
579
 
715
- **Q: Does this work with Prisma Edge Runtime?**
716
- A: Yes, the generated schemas are compatible with Prisma Edge Runtime.
580
+ ### Global and Model-Specific Exclusions
717
581
 
718
- **Q: Can I use this with databases other than the officially supported ones?**
719
- A: The generator supports all Prisma-compatible databases. Custom databases should work if Prisma supports them.
582
+ ```typescript
583
+ // Configuration-based exclusion
584
+ const config = {
585
+ globalExclusions: {
586
+ input: ["id", "createdAt", "updatedAt"],
587
+ result: ["password", "hashedPassword"],
588
+ pure: []
589
+ },
590
+ models: {
591
+ User: {
592
+ variants: {
593
+ input: { excludeFields: ["role", "permissions"] },
594
+ result: { excludeFields: ["password", "sessionToken"] }
595
+ }
596
+ }
597
+ }
598
+ };
599
+ ```
720
600
 
721
- **Q: How do I handle enum validation?**
722
- A: Enums are automatically converted to Zod enum schemas and placed in the `enums/` directory.
601
+ ### Prisma Schema Exclusions
723
602
 
724
- **Q: Can I exclude certain fields from validation?**
725
- A: Use Prisma's `@ignore` directive or model-level hiding with `@@Gen.model(hide: true)`.
603
+ ```prisma
604
+ model User {
605
+ id Int @id @default(autoincrement())
606
+ email String @unique
607
+ password String // Excluded from result schemas
608
+ role String // Excluded from input schemas
609
+ /// @@Gen.model(hide: true) // Hide entire model
610
+ posts Post[]
611
+ }
612
+ ```
726
613
 
727
- ### Getting Help
614
+ </details>
728
615
 
729
- - 🐛 **Bug Reports**: [Create a bug report](https://github.com/omar-dulaimi/prisma-zod-generator/issues/new)
730
- - 💡 **Feature Requests**: [Request a feature](https://github.com/omar-dulaimi/prisma-zod-generator/issues/new)
731
- - 💬 **Discussions**: [Join the discussion](https://github.com/omar-dulaimi/prisma-zod-generator/discussions)
616
+ <details>
617
+ <summary><strong>📝 @zod Comment Annotations</strong></summary>
732
618
 
733
- ## 🤝 Contributing
619
+ ### Inline Validation Rules
620
+
621
+ Add validation directly in your Prisma schema:
622
+
623
+ ```prisma
624
+ model User {
625
+ id Int @id @default(autoincrement())
626
+ email String @unique /// @zod.email()
627
+ name String? /// @zod.min(2).max(50)
628
+ age Int? /// @zod.min(0).max(120)
629
+ username String @unique /// @zod.regex(/^[a-zA-Z0-9_]+$/)
630
+ website String? /// @zod.url().optional()
631
+ }
632
+ ```
633
+
634
+ Generated schema with validations:
635
+
636
+ ```typescript
637
+ export const UserCreateInputSchema = z.object({
638
+ email: z.string().email(),
639
+ name: z.string().min(2).max(50).optional(),
640
+ age: z.number().int().min(0).max(120).optional(),
641
+ username: z.string().regex(/^[a-zA-Z0-9_]+$/),
642
+ website: z.string().url().optional()
643
+ });
644
+ ```
645
+
646
+ ### Supported @zod Annotations
647
+
648
+ ```prisma
649
+ // String validations
650
+ field String /// @zod.email()
651
+ field String /// @zod.url()
652
+ field String /// @zod.regex(/pattern/)
653
+ field String /// @zod.min(2).max(50)
654
+
655
+ // Number validations
656
+ field Int /// @zod.min(0).max(100)
657
+ field Float /// @zod.positive()
658
+
659
+ // Custom validations
660
+ field String /// @zod.custom(z.string().transform(s => s.toLowerCase()))
661
+ ```
662
+
663
+ </details>
664
+
665
+ <details>
666
+ <summary><strong>🗄️ Multi-Database Provider Support</strong></summary>
667
+
668
+ ### Database-Specific Optimizations
669
+
670
+ ```typescript
671
+ // PostgreSQL - Advanced types supported
672
+ const pgUser = z.object({
673
+ id: z.number().int(),
674
+ metadata: z.record(z.unknown()), // JSON type
675
+ tags: z.array(z.string()), // Array type
676
+ balance: z.number() // Decimal type
677
+ });
678
+
679
+ // MongoDB - Document structure
680
+ const mongoUser = z.object({
681
+ id: z.string(), // ObjectId as string
682
+ embedded: z.object({ // Embedded documents
683
+ profile: z.object({
684
+ bio: z.string().optional()
685
+ })
686
+ }).optional()
687
+ });
688
+
689
+ // MySQL - Optimized for relational data
690
+ const mysqlUser = z.object({
691
+ id: z.number().int(),
692
+ createdAt: z.date(),
693
+ updatedAt: z.date()
694
+ });
695
+ ```
696
+
697
+ ### Supported Providers
698
+
699
+ - **PostgreSQL** - Full advanced type support
700
+ - **MySQL** - Complete compatibility
701
+ - **MongoDB** - Native document schemas
702
+ - **SQLite** - Development & testing optimized
703
+ - **SQL Server** - Enterprise features
704
+ - **CockroachDB** - Distributed database support
705
+
706
+ </details>
707
+
708
+ <details>
709
+ <summary><strong>🔧 ESM Import Handling</strong></summary>
710
+
711
+ ### Modern ES Module Support
712
+
713
+ Full ESM compatibility with automatic file extension handling:
714
+
715
+ ```prisma
716
+ generator client {
717
+ provider = "prisma-client"
718
+ output = "./src/generated/client"
719
+ moduleFormat = "esm"
720
+ importFileExtension = "js" # Auto-handled
721
+ }
722
+ ```
723
+
724
+ Generated imports include proper extensions:
725
+
726
+ ```typescript
727
+ import { User } from '../client/index.js'; // Auto-generated
728
+ import { z } from 'zod';
729
+ ```
730
+
731
+ ### Import Configuration
732
+
733
+ ```json
734
+ {
735
+ "esm": {
736
+ "enabled": true,
737
+ "fileExtension": ".js",
738
+ "importExtension": ".js"
739
+ }
740
+ }
741
+ ```
742
+
743
+ </details>
744
+
745
+ <details>
746
+ <summary><strong>⚡ Performance Optimization</strong></summary>
747
+
748
+ ### Built-in Optimizations
749
+
750
+ ```typescript
751
+ // Lazy loading for circular references
752
+ const UserSchema = z.lazy(() => z.object({
753
+ id: z.number().int(),
754
+ posts: z.array(PostSchema).optional()
755
+ }));
756
+
757
+ // Selective generation
758
+ const config = {
759
+ models: {
760
+ AuditLog: { enabled: false }, // Skip audit tables
761
+ Migration: { enabled: false }, // Skip migration tables
762
+ User: {
763
+ enabled: true,
764
+ operations: ["findMany", "create", "update"] // Only needed operations
765
+ }
766
+ }
767
+ };
768
+ ```
769
+
770
+ ### Performance Tips
771
+
772
+ - Use `minimal` mode for faster generation
773
+ - Exclude unused models and operations
774
+ - Enable lazy loading for complex relationships
775
+ - Cache generated schemas in production
776
+
777
+ </details>
778
+
779
+ <details>
780
+ <summary><strong>🔐 API Security & Validation Patterns</strong></summary>
781
+
782
+ ### Input Sanitization
783
+
784
+ ```typescript
785
+ export const sanitizeUserInput = (data: unknown) => {
786
+ return UserCreateInputSchema
787
+ .omit({ id: true }) // Remove ID from input
788
+ .extend({
789
+ email: z.string().email().toLowerCase() // Normalize email
790
+ })
791
+ .parse(data);
792
+ };
793
+ ```
794
+
795
+ ### Role-Based Field Filtering
796
+
797
+ ```typescript
798
+ export const getUserForRole = (user: User, role: 'admin' | 'user') => {
799
+ const baseSchema = UserResultSchema;
800
+
801
+ if (role === 'user') {
802
+ return baseSchema.omit({
803
+ email: true,
804
+ role: true,
805
+ permissions: true
806
+ }).parse(user);
807
+ }
808
+
809
+ return baseSchema.parse(user);
810
+ };
811
+ ```
812
+
813
+ ### Complete API Endpoint Validation
814
+
815
+ ```typescript
816
+ app.post('/users', async (req, res) => {
817
+ try {
818
+ const userData = UserCreateInputSchema.parse(req.body);
819
+ const user = await prisma.user.create({ data: userData });
820
+ const response = UserResultSchema.parse(user);
821
+ res.json(response);
822
+ } catch (error) {
823
+ if (error instanceof z.ZodError) {
824
+ return res.status(400).json({
825
+ errors: error.errors.map(e => ({
826
+ field: e.path.join('.'),
827
+ message: e.message
828
+ }))
829
+ });
830
+ }
831
+ }
832
+ });
833
+ ```
834
+
835
+ </details>
836
+
837
+ ---
838
+
839
+ ## ⚙️ Configuration
840
+
841
+ <details>
842
+ <summary><strong>🔧 Configuration Options</strong></summary>
843
+
844
+ ### Basic Configuration
845
+
846
+ | Option | Description | Type | Default |
847
+ |--------|-------------|------|---------|
848
+ | `output` | Output directory for generated files | `string` | `"./generated"` |
849
+ | `isGenerateSelect` | Generate Select-related schemas | `boolean` | `false` |
850
+ | `isGenerateInclude` | Generate Include-related schemas | `boolean` | `false` |
851
+ | `exportTypedSchemas` | Export z.ZodType versions (type-safe) | `boolean` | `true` |
852
+ | `exportZodSchemas` | Export pure Zod versions (method-friendly) | `boolean` | `true` |
853
+ | `typedSchemaSuffix` | Suffix for typed schemas | `string` | `"Schema"` |
854
+ | `zodSchemaSuffix` | Suffix for Zod schemas | `string` | `"ZodSchema"` |
855
+ | `useMultipleFiles` | Output multiple files (true) or single bundle (false) | `boolean` | `true` |
856
+ | `singleFileName` | Name of the single-file bundle when `useMultipleFiles=false` | `string` | `"schemas.ts"` |
857
+ | `placeSingleFileAtRoot` | When `useMultipleFiles=false`, place the single file at the generator output root instead of a `schemas/` subfolder | `boolean` | `true` |
858
+
859
+ ### Advanced Configuration
860
+
861
+ ```prisma
862
+ generator zod {
863
+ provider = "prisma-zod-generator"
864
+ output = "./src/schemas"
865
+ // File output mode
866
+ // true -> multiple files (default)
867
+ // false -> single file bundle (see singleFileName below)
868
+ useMultipleFiles = true
869
+ // Optional: name of the single-file bundle when useMultipleFiles = false
870
+ // Defaults to "schemas.ts"
871
+ singleFileName = "schemas.ts"
872
+ // Optional: when useMultipleFiles = false, place the single file at the
873
+ // generator output root (true) or inside a schemas/ subdir (false)
874
+ placeSingleFileAtRoot = true
875
+ isGenerateSelect = true
876
+ isGenerateInclude = true
877
+ config = "./zod-config.json"
878
+ }
879
+ ```
880
+
881
+ ### Model Customizations
882
+
883
+ ```prisma
884
+ /// @@Gen.model(hide: true)
885
+ model InternalLog {
886
+ id Int @id @default(autoincrement())
887
+ message String
888
+ createdAt DateTime @default(now())
889
+ }
890
+ ```
891
+
892
+ ### JSON Configuration File
893
+
894
+ ```json
895
+ {
896
+ "mode": "custom",
897
+ "output": "./generated/schemas",
898
+ "relationModel": true,
899
+ "modelCase": "PascalCase",
900
+ "modelSuffix": "Schema",
901
+ "useMultipleFiles": true,
902
+ "placeSingleFileAtRoot": true,
903
+ "createInputTypes": true,
904
+ "addIncludeType": true,
905
+ "addSelectType": true,
906
+ "validateWhereUniqueInput": true,
907
+ "prismaClientPath": "@prisma/client"
908
+ }
909
+ ```
910
+
911
+ </details>
912
+
913
+ ---
914
+
915
+ ## 📖 API Reference
916
+
917
+ ## ⚙️ Configuration sources, precedence, and availability
918
+
919
+ This generator accepts configuration from two sources. When the same option is provided in multiple places, the value is resolved using a simple precedence.
920
+
921
+ ### Sources
922
+
923
+ - Prisma generator block (schema.prisma)
924
+ - Standard Prisma fields like `output`.
925
+ - Simple override flags/strings (e.g., `useMultipleFiles`, `singleFileName`, etc.).
926
+ - Optional `config = "./zod-generator.config.json"` to point to a JSON file.
927
+ - JSON config file (recommended for complex/nested settings)
928
+ - Full configuration surface, including nested structures like `models` and `variants`.
929
+ - Can be provided explicitly via `config = "./path.json"` or auto-discovered (e.g., `zod-generator.config.json`, `.zod-generator.json`).
930
+
931
+ ### Precedence (highest → lowest)
932
+
933
+ 1) Prisma generator block options (direct attributes in `generator zod { ... }`)
934
+ 2) JSON config file (explicit or auto-discovered)
935
+ 3) Built-in defaults (computed based on `mode`, etc.)
936
+
937
+ Notes and special cases:
938
+ - Output path: The Prisma generator’s `output` always decides where files go. Any `output` set in the JSON config is ignored.
939
+ - Minimal mode: If `mode = "minimal"` (or legacy `minimal = true`), select/include schemas are forcibly disabled and many complex nested inputs are suppressed to speed up generation and shrink output.
940
+ - Legacy flags: `isGenerateSelect` / `isGenerateInclude` (Prisma block) override the newer `addSelectType` / `addIncludeType` (config JSON). Minimal mode will still force them off.
941
+
942
+ ### Option availability matrix
943
+
944
+ | Option | Prisma generator block | JSON config file | Notes |
945
+ |---|---|---|---|
946
+ | `output` | Yes (authoritative) | Ignored if present | Use the Prisma generator `output` only |
947
+ | `useMultipleFiles` | Yes | Yes | `false` enables strict single-file mode |
948
+ | `singleFileName` | Yes | Yes | File name for the single bundle (default `schemas.ts`) |
949
+ | `placeSingleFileAtRoot` | Yes | Yes | Place single file at output root (true, default) or under `schemas/` (false) |
950
+ | `placeArrayVariantsAtRoot` | Yes | Yes | For array-based variants placement (root vs `variants/`) |
951
+ | `mode` (`full|minimal|custom`) | Yes | Yes | Minimal mode applies opinionated defaults |
952
+ | `pureModels` | Yes | Yes | Generates `models/` set when multi-file; N/A in single-file (content is bundled) |
953
+ | `globalExclusions` | — | Yes | Object keyed by variant (`input`, `result`, `pure`) |
954
+ | `variants` (object-based) | — | Yes | Nested structure; configure `pure/input/result` |
955
+ | `models.*` (per-model) | — | Yes | Nested per-model rules, operations, and variant overrides |
956
+ | `addSelectType` / `addIncludeType` | Yes (as legacy `isGenerateSelect` / `isGenerateInclude`) | Yes | Prisma block flags override the JSON values; minimal mode forces off |
957
+ | `formatGeneratedSchemas` | — | Yes | Formatting can be skipped for speed (default: false) |
958
+ | `config` (path to JSON) | Yes | — | Points to the JSON file; not a config value itself |
959
+
960
+ Example: Prisma block overrides JSON file
961
+
962
+ ```prisma
963
+ generator zod {
964
+ provider = "prisma-zod-generator"
965
+ output = "./generated"
966
+ // Overrides values from the JSON config below
967
+ useMultipleFiles = false
968
+ singleFileName = "bundle.ts"
969
+ placeSingleFileAtRoot = true
970
+ // Load additional (nested) settings from a JSON file
971
+ config = "./zod-generator.config.json"
972
+ }
973
+ ```
974
+
975
+ When both sources specify the same simple option (e.g., `useMultipleFiles`), the Prisma block wins. Nested settings (like `models` and `variants`) should live in the JSON file.
976
+
977
+ ### How @zod schema comments fit into precedence
978
+
979
+ Inline `@zod` comments in your Prisma schema are not a separate “config source,” but they do affect field-level validation and are always respected when that field is generated.
980
+
981
+ - Scope: Applies only to the field where the comment appears, and only in schemas that include that field (subject to filtering, variants, minimal mode).
982
+ - Merge behavior: Field validation is built by combining pieces. In practice, the chain is composed of the base Zod type plus any optional/nullable handling, any config-driven validations (e.g., variant `additionalValidation`), and your `@zod` comment directives. If multiple validations of the same kind are present, they’re appended in order; the latter call wins when there’s a conflict.
983
+ - Not a global override: `@zod` comments do not override global settings like `output`, `mode`, or file layout; they only enrich the field’s Zod chain.
984
+ - Filtering/minimal mode: If a field or schema is excluded by filters/variants/minimal mode, its comments simply won’t apply because that schema isn’t emitted.
985
+
986
+ See the “@zod Comment Annotations” section for syntax and examples.
987
+
988
+ <details>
989
+ <summary><strong>📚 Generated Schema Types</strong></summary>
990
+
991
+ ### Operation Schemas
992
+
993
+ - **Create Operations**: `ModelCreateOneSchema`, `ModelCreateManySchema`
994
+ - **Read Operations**: `ModelFindManySchema`, `ModelFindUniqueSchema`, `ModelFindFirstSchema`
995
+ - **Update Operations**: `ModelUpdateOneSchema`, `ModelUpdateManySchema`, `ModelUpsertSchema`
996
+ - **Delete Operations**: `ModelDeleteOneSchema`, `ModelDeleteManySchema`
997
+ - **Aggregate Operations**: `ModelAggregateSchema`, `ModelGroupBySchema`
998
+
999
+ ### Input Object Schemas
1000
+
1001
+ - **Create Inputs**: `ModelCreateInputObjectSchema`, `ModelCreateNestedInputObjectSchema`
1002
+ - **Update Inputs**: `ModelUpdateInputObjectSchema`, `ModelUpdateNestedInputObjectSchema`
1003
+ - **Where Inputs**: `ModelWhereInputObjectSchema`, `ModelWhereUniqueInputObjectSchema`
1004
+ - **Order Inputs**: `ModelOrderByInputObjectSchema`
1005
+
1006
+ ### Select & Include Schemas
1007
+
1008
+ When enabled with `isGenerateSelect: true` and `isGenerateInclude: true`:
1009
+ - **Select Schemas**: `ModelSelectObjectSchema`
1010
+ - **Include Schemas**: `ModelIncludeObjectSchema`
1011
+
1012
+ ### Schema Naming Convention
1013
+
1014
+ All generated schemas follow this pattern:
1015
+ ```
1016
+ {ModelName}{Operation}{Type}Schema
1017
+ ```
1018
+
1019
+ Examples:
1020
+ - `UserCreateOneSchema` - Schema for creating a single user
1021
+ - `PostFindManyArgsSchema` - Schema for finding multiple posts with arguments
1022
+ - `UserWhereInputObjectSchema` - Schema for user where conditions
1023
+
1024
+ </details>
1025
+
1026
+ ---
1027
+
1028
+ ## 🌐 Framework Examples
1029
+
1030
+ <details>
1031
+ <summary><strong>🚀 Next.js Integration</strong></summary>
1032
+
1033
+ ### API Routes
1034
+
1035
+ ```typescript
1036
+ // pages/api/users.ts
1037
+ import type { NextApiRequest, NextApiResponse } from 'next';
1038
+ import { UserCreateOneSchema } from '../../generated/schemas';
1039
+
1040
+ export default async function handler(req: NextApiRequest, res: NextApiResponse) {
1041
+ if (req.method === 'POST') {
1042
+ try {
1043
+ const userData = UserCreateOneSchema.parse(req.body);
1044
+ const user = await prisma.user.create(userData);
1045
+ res.status(201).json(user);
1046
+ } catch (error) {
1047
+ res.status(400).json({ error: error.message });
1048
+ }
1049
+ }
1050
+ }
1051
+ ```
1052
+
1053
+ ### App Router (Next.js 13+)
1054
+
1055
+ ```typescript
1056
+ // app/api/users/route.ts
1057
+ import { NextRequest, NextResponse } from 'next/server';
1058
+ import { UserCreateOneSchema } from '@/generated/schemas';
1059
+
1060
+ export async function POST(request: NextRequest) {
1061
+ try {
1062
+ const body = await request.json();
1063
+ const userData = UserCreateOneSchema.parse(body);
1064
+ const user = await prisma.user.create(userData);
1065
+ return NextResponse.json(user);
1066
+ } catch (error) {
1067
+ return NextResponse.json({ error: error.message }, { status: 400 });
1068
+ }
1069
+ }
1070
+ ```
1071
+
1072
+ </details>
1073
+
1074
+ <details>
1075
+ <summary><strong>⚡ tRPC Integration</strong></summary>
1076
+
1077
+ ```typescript
1078
+ import { z } from 'zod';
1079
+ import { PostCreateOneSchema, PostFindManySchema } from './generated/schemas';
1080
+
1081
+ export const postRouter = router({
1082
+ create: publicProcedure
1083
+ .input(PostCreateOneSchema)
1084
+ .mutation(({ input }) => {
1085
+ return prisma.post.create(input);
1086
+ }),
1087
+
1088
+ list: publicProcedure
1089
+ .input(PostFindManySchema)
1090
+ .query(({ input }) => {
1091
+ return prisma.post.findMany(input);
1092
+ }),
1093
+ });
1094
+ ```
1095
+
1096
+ </details>
1097
+
1098
+ <details>
1099
+ <summary><strong>🛠️ Fastify Integration</strong></summary>
1100
+
1101
+ ```typescript
1102
+ import fastify from 'fastify';
1103
+ import { UserCreateOneSchema } from './generated/schemas';
1104
+
1105
+ const server = fastify();
734
1106
 
735
- Contributions are welcome! Here's how you can help:
1107
+ server.post('/users', {
1108
+ schema: {
1109
+ body: UserCreateOneSchema
1110
+ }
1111
+ }, async (request, reply) => {
1112
+ const user = await prisma.user.create(request.body);
1113
+ return user;
1114
+ });
1115
+ ```
1116
+
1117
+ </details>
1118
+
1119
+ <details>
1120
+ <summary><strong>🌐 Express.js Integration</strong></summary>
1121
+
1122
+ ```typescript
1123
+ import express from 'express';
1124
+ import { UserCreateOneSchema, UserFindManySchema } from './generated/schemas';
1125
+
1126
+ const app = express();
1127
+
1128
+ // Create user with validation
1129
+ app.post('/users', async (req, res) => {
1130
+ try {
1131
+ const data = UserCreateOneSchema.parse(req.body);
1132
+ const user = await prisma.user.create(data);
1133
+ res.json(user);
1134
+ } catch (error) {
1135
+ if (error instanceof z.ZodError) {
1136
+ return res.status(400).json({ errors: error.errors });
1137
+ }
1138
+ res.status(500).json({ error: 'Internal server error' });
1139
+ }
1140
+ });
1141
+
1142
+ // Query with validation
1143
+ app.get('/users', async (req, res) => {
1144
+ const query = UserFindManySchema.parse(req.query);
1145
+ const users = await prisma.user.findMany(query);
1146
+ res.json(users);
1147
+ });
1148
+ ```
1149
+
1150
+ </details>
1151
+
1152
+ ---
1153
+
1154
+ ## 🧪 Testing & Development
1155
+
1156
+ <details>
1157
+ <summary><strong>🔬 Testing Infrastructure</strong></summary>
1158
+
1159
+ ### Test Suite Overview
1160
+
1161
+ We maintain **enterprise-grade testing standards** with comprehensive coverage:
1162
+
1163
+ #### 📊 **Test Statistics**
1164
+ - **📊 80+ Tests Passing** - Comprehensive validation across all features
1165
+ - **🔍 5,239 Schemas Validated** - Massive multi-provider testing
1166
+ - **✅ 100% TypeScript Compilation** - Zero compilation errors guaranteed
1167
+ - **🛡️ Zero ESLint Issues** - Clean, maintainable code quality
1168
+
1169
+ #### 📋 **Test Categories**
1170
+
1171
+ ```bash
1172
+ # Core infrastructure tests
1173
+ npm run test:core # Configuration & integration tests
1174
+ npm run test:esm # ESM import handling tests
1175
+ npm run test:comprehensive # Multi-provider schema validation
1176
+
1177
+ # Feature-specific tests
1178
+ npm run test:config # Configuration system validation
1179
+ npm run test:variants # Schema variant generation
1180
+ npm run test:filtering # Model/field filtering logic
1181
+ npm run test:pure-models # Pure model schema generation
1182
+ npm run test:result-schemas # Result schema validation
1183
+ npm run test:zod-comments # @zod comment parsing
1184
+ npm run test:field-exclusion # Field exclusion system
1185
+
1186
+ # Advanced testing
1187
+ npm run test:integration # Full generation pipeline tests
1188
+ npm run test:multi-provider # All database provider validation
1189
+ npm run test:performance # Schema generation performance
1190
+ npm run test:coverage # Code coverage analysis
1191
+ ```
1192
+
1193
+ </details>
1194
+
1195
+ <details>
1196
+ <summary><strong>🧪 Testing Integration</strong></summary>
1197
+
1198
+ ### Schema Testing Utilities
1199
+
1200
+ ```typescript
1201
+ import { SchemaTestUtils } from './test-utils';
1202
+
1203
+ // Validate schema structure
1204
+ SchemaTestUtils.testValidData(UserCreateInputSchema, {
1205
+ email: 'test@example.com',
1206
+ name: 'Test User'
1207
+ });
1208
+
1209
+ // Test boundary conditions
1210
+ SchemaTestUtils.testBoundaryValues(UserCreateInputSchema, [
1211
+ { value: { email: 'invalid-email' }, shouldPass: false },
1212
+ { value: { name: 'x'.repeat(51) }, shouldPass: false },
1213
+ { value: { name: 'Valid Name' }, shouldPass: true }
1214
+ ]);
1215
+
1216
+ // Performance testing
1217
+ const performance = SchemaTestUtils.performanceTest(
1218
+ UserCreateInputSchema,
1219
+ validUserData,
1220
+ 1000 // iterations
1221
+ );
1222
+ console.log(`Avg validation time: ${performance.avgTime}ms`);
1223
+ ```
736
1224
 
737
1225
  ### Development Setup
738
1226
 
739
- 1. **Fork and clone the repository**
740
1227
  ```bash
1228
+ # Clone and setup
741
1229
  git clone https://github.com/your-username/prisma-zod-generator.git
742
1230
  cd prisma-zod-generator
1231
+ npm install
1232
+
1233
+ # Development build
1234
+ npm run gen-example
1235
+
1236
+ # Run tests
1237
+ npm test
1238
+
1239
+ # Code quality
1240
+ npm run lint # Check and fix linting issues
1241
+ npm run format # Format code with Prettier
743
1242
  ```
744
1243
 
745
- 2. **Install dependencies**
1244
+ </details>
1245
+
1246
+ <details>
1247
+ <summary><strong>📈 Multi-Database Provider Validation</strong></summary>
1248
+
1249
+ Our test suite validates schemas across **6 database providers**:
1250
+
1251
+ | Provider | Schemas Validated | Status |
1252
+ |----------|------------------|---------|
1253
+ | **PostgreSQL** | 1,020 schemas | ✅ |
1254
+ | **MySQL** | 1,326 schemas | ✅ |
1255
+ | **MongoDB** | 855 schemas | ✅ |
1256
+ | **SQLite** | 1,409 schemas | ✅ |
1257
+ | **SQL Server** | 622 schemas | ✅ |
1258
+ | **Default** | Additional schemas | ✅ |
1259
+
1260
+ </details>
1261
+
1262
+ ---
1263
+
1264
+ ## 🔍 Troubleshooting
1265
+
1266
+ <details>
1267
+ <summary><strong>🚨 Common Issues & Solutions</strong></summary>
1268
+
1269
+ ### Generator Compatibility Errors
1270
+
1271
+ **Issue**: Cannot find compatible Prisma generator
746
1272
  ```bash
747
- npm install
1273
+ Error: No compatible Prisma client generator found
748
1274
  ```
749
1275
 
750
- 3. **Run the development build**
751
- ```bash
752
- npm run gen-example
1276
+ **Solution**: Ensure you have a supported generator in your schema:
1277
+ ```prisma
1278
+ generator client {
1279
+ provider = "prisma-client-js" // or "prisma-client"
1280
+ }
1281
+
1282
+ generator zod {
1283
+ provider = "prisma-zod-generator"
1284
+ output = "./generated/schemas"
1285
+ }
753
1286
  ```
754
1287
 
755
- 4. **Run tests**
756
- ```bash
757
- npm test
1288
+ ### Module Resolution Errors
1289
+
1290
+ **Issue**: `Cannot find module './generated/schemas'`
1291
+
1292
+ **Solutions**:
1293
+ 1. Run `npx prisma generate` after adding the generator
1294
+ 2. Check that your output path is correct
1295
+ 3. Verify the generator completed successfully
1296
+
1297
+ ### TypeScript Compilation Errors
1298
+
1299
+ **Issue**: Generated schemas have TypeScript errors
1300
+
1301
+ **Solutions**:
1302
+ 1. Enable strict mode in `tsconfig.json`:
1303
+ ```json
1304
+ {
1305
+ "compilerOptions": {
1306
+ "strict": true,
1307
+ }
1308
+ }
1309
+ ```
1310
+ 2. Update dependencies: `npm update prisma-zod-generator prisma zod`
1311
+ 3. Clear build cache and regenerate
1312
+
1313
+ ### Generation Performance Issues
1314
+
1315
+ **Issue**: Slow generation for large schemas
1316
+
1317
+ **Solutions**:
1318
+ 1. Use minimal mode:
1319
+ ```json
1320
+ {
1321
+ "mode": "minimal",
1322
+ "models": {
1323
+ "AuditLog": { "enabled": false },
1324
+ "Migration": { "enabled": false }
1325
+ }
1326
+ }
758
1327
  ```
1328
+ 2. Exclude unnecessary operations
1329
+ 3. Enable selective model generation
1330
+
1331
+ </details>
759
1332
 
760
- ### Testing
1333
+ <details>
1334
+ <summary><strong>💡 Performance Optimization Tips</strong></summary>
761
1335
 
762
- We have comprehensive tests covering:
763
- - **Unit Tests**: Core transformation logic
764
- - **Integration Tests**: End-to-end schema generation
765
- - **Multi-Provider Tests**: All database providers
766
- - **Performance Tests**: Large schema handling
1336
+ ### Large Schema Optimization
1337
+
1338
+ For projects with 50+ models:
1339
+ - Use selective generation with model hiding
1340
+ - Split schemas into multiple files
1341
+ - Implement lazy loading for schemas
1342
+ - Consider minimal mode for faster builds
1343
+
1344
+ ### Build Time Optimization
1345
+
1346
+ ```json
1347
+ {
1348
+ "mode": "minimal",
1349
+ "models": {
1350
+ "User": {
1351
+ "operations": ["findMany", "create", "update"]
1352
+ }
1353
+ }
1354
+ }
1355
+ ```
1356
+
1357
+ ### Production Deployment
1358
+
1359
+ ```typescript
1360
+ // Environment-specific configuration
1361
+ const productionConfig = {
1362
+ mode: 'minimal',
1363
+ globalExclusions: {
1364
+ result: ['password', 'sessionToken', 'internalNotes']
1365
+ }
1366
+ };
1367
+ ```
1368
+
1369
+ </details>
1370
+
1371
+ <details>
1372
+ <summary><strong>❓ Frequently Asked Questions</strong></summary>
1373
+
1374
+ **Q: Can I customize the generated validation rules?**
1375
+ A: Modify your Prisma schema with `@zod` comments or use configuration options to customize validation.
1376
+
1377
+ **Q: Does this work with Prisma Edge Runtime?**
1378
+ A: Yes, generated schemas are compatible with Prisma Edge Runtime.
1379
+
1380
+ **Q: How do I handle circular references?**
1381
+ A: The generator automatically uses lazy loading for circular relationships.
1382
+
1383
+ **Q: Can I exclude certain fields from validation?**
1384
+ A: Yes, use the `globalExclusions` or model-specific `excludeFields` configuration.
1385
+
1386
+ **Q: How do I handle enum validation?**
1387
+ A: Enums are automatically converted to Zod enum schemas in the `enums/` directory.
1388
+
1389
+ </details>
1390
+
1391
+ ---
1392
+
1393
+ ## 🤝 Contributing
1394
+
1395
+ <details>
1396
+ <summary><strong>🛠️ Development Guidelines</strong></summary>
1397
+
1398
+
1399
+ <details>
1400
+ <summary><strong>🚀 Release Process</strong></summary>
1401
+
1402
+ This project uses semantic versioning and automated releases:
1403
+
1404
+ - Patch: Bug fixes and small improvements
1405
+ - Minor: New features and enhancements
1406
+ - Major: Breaking changes
1407
+
1408
+ Helpful commands:
767
1409
 
768
- Run specific test suites:
769
1410
  ```bash
770
- npm run test:basic # Basic functionality
771
- npm run test:multi # Multi-provider testing
772
- npm run test:coverage # Coverage reports
773
- npm run test:comprehensive # Full test suite
1411
+ npm run prerelease # Build, type-check, lint
1412
+ npm run release:dry # Preview the next release
774
1413
  ```
775
1414
 
776
- ### Contribution Guidelines
1415
+ </details>
1416
+ ### Contribution Process
777
1417
 
778
1418
  1. **Create an issue** for bugs or feature requests
779
- 2. **Follow the existing code style** (ESLint + Prettier)
780
- 3. **Add tests** for new functionality
781
- 4. **Update documentation** as needed
782
- 5. **Submit a pull request** with a clear description
1419
+ 2. **Fork and clone** the repository
1420
+ 3. **Follow existing code style** (ESLint + Prettier)
1421
+ 4. **Add comprehensive tests** for new functionality
1422
+ 5. **Update documentation** as needed
1423
+ 6. **Submit a pull request** with clear description
783
1424
 
784
- ### Code Style
1425
+ ### Code Quality Standards
785
1426
 
786
- We use ESLint and Prettier for consistent code formatting:
787
1427
  ```bash
788
1428
  npm run lint # Check and fix linting issues
789
1429
  npm run format # Format code with Prettier
1430
+ npm test # Run comprehensive test suite
790
1431
  ```
791
1432
 
792
- ### Release Process
1433
+ ### Testing Requirements
793
1434
 
794
- This project uses semantic versioning and automated releases:
795
- - **Patch**: Bug fixes and small improvements
796
- - **Minor**: New features and enhancements
797
- - **Major**: Breaking changes
1435
+ When contributing new features:
1436
+ 1. **Write tests first** - TDD approach
1437
+ 2. **Test all edge cases** - Comprehensive scenarios
1438
+ 3. **Validate across providers** - Multi-database compatibility
1439
+ 4. **Performance testing** - Ensure scalability
1440
+ 5. **Integration testing** - End-to-end validation
1441
+
1442
+ </details>
1443
+
1444
+ ---
798
1445
 
799
1446
  ## 📄 License
800
1447
 
801
1448
  This project is licensed under the [MIT License](LICENSE).
802
1449
 
1450
+ ---
1451
+
803
1452
  ## 🔗 Related Projects
804
1453
 
805
1454
  - [prisma-trpc-generator](https://github.com/omar-dulaimi/prisma-trpc-generator) - Generate tRPC routers from Prisma schema
806
1455
  - [Prisma](https://github.com/prisma/prisma) - Database toolkit and ORM
807
1456
  - [Zod](https://github.com/colinhacks/zod) - TypeScript-first schema validation
808
1457
 
809
- ## 🙏 Acknowledgments
810
-
811
- - [Prisma](https://github.com/prisma/prisma) - Modern database toolkit
812
- - [Zod](https://github.com/colinhacks/zod) - TypeScript-first schema validation
813
- - All our [contributors](https://github.com/omar-dulaimi/prisma-zod-generator/graphs/contributors)
814
-
815
- ---
816
-
817
- <br>
818
-
819
1458
  ---
820
1459
 
821
1460
  <div align="center">
@@ -828,23 +1467,6 @@ This project is licensed under the [MIT License](LICENSE).
828
1467
 
829
1468
  <br><br>
830
1469
 
831
- <table>
832
- <tr>
833
- <td align="center">
834
- <img src="https://img.shields.io/badge/💎-Latest_Stable-success?style=for-the-badge&logo=npm" alt="Stable">
835
- <br>
836
- <code>v1.0.0</code>
837
- </td>
838
- <td align="center">
839
- <img src="https://img.shields.io/badge/📦-Legacy_Version-lightgrey?style=for-the-badge&logo=archive" alt="Legacy">
840
- <br>
841
- <code>v0.8.13</code>
842
- </td>
843
- </tr>
844
- </table>
845
-
846
- <br>
847
-
848
1470
  <p>
849
1471
  <strong>Made with ❤️ by</strong>
850
1472
  <a href="https://github.com/omar-dulaimi">
@@ -854,4 +1476,4 @@ This project is licensed under the [MIT License](LICENSE).
854
1476
 
855
1477
  <p><em>⚡ Accelerating Prisma development, one schema at a time</em></p>
856
1478
 
857
- </div>
1479
+ </div>