0
# @prisma/generator-helper
1
2
@prisma/generator-helper provides a standardized way to build custom code generation tools that extend Prisma's capabilities. It abstracts the complexity of the generator protocol by managing JSON-RPC communication between Prisma CLI and generator processes, offering interfaces for manifest retrieval and code generation handlers.
3
4
## Package Information
5
6
- **Package Name**: @prisma/generator-helper
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @prisma/generator-helper`
10
11
## Core Imports
12
13
```typescript
14
import { generatorHandler } from "@prisma/generator-helper";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const { generatorHandler } = require("@prisma/generator-helper");
21
```
22
23
Advanced imports:
24
25
```typescript
26
import {
27
generatorHandler,
28
GeneratorProcess,
29
GeneratorError
30
} from "@prisma/generator-helper";
31
```
32
33
## Basic Usage
34
35
```typescript
36
import { generatorHandler } from "@prisma/generator-helper";
37
38
// Simple generator implementation
39
generatorHandler({
40
onManifest: () => ({
41
prettyName: "My Custom Generator",
42
defaultOutput: "./generated"
43
}),
44
onGenerate: async (options) => {
45
// Access the Prisma schema structure
46
const { dmmf } = options;
47
48
// Generate code based on models
49
dmmf.datamodel.models.forEach(model => {
50
console.log(`Generating code for model: ${model.name}`);
51
// Your code generation logic here
52
});
53
54
// Write generated files to options.generator.output.value
55
}
56
});
57
```
58
59
## Architecture
60
61
@prisma/generator-helper is built around several key components:
62
63
- **Handler Interface**: Simple callback-based API for implementing generators with `onGenerate` and optional `onManifest` methods
64
- **JSON-RPC Protocol**: Automatic handling of communication between Prisma CLI and generator processes over stdin/stderr
65
- **Process Management**: `GeneratorProcess` class for advanced scenarios requiring direct process control
66
- **Type Integration**: Full TypeScript support with types from `@prisma/generator` and `@prisma/dmmf` packages
67
- **Error Handling**: Standardized error reporting with `GeneratorError` class and automatic exception marshaling
68
69
## Capabilities
70
71
### Generator Handler
72
73
Core handler function that sets up JSON-RPC communication and manages the generator lifecycle. Use this for most generator implementations.
74
75
```typescript { .api }
76
/**
77
* Sets up JSON-RPC communication for a Prisma generator
78
* @param handler - Handler object with lifecycle methods
79
*/
80
function generatorHandler(handler: Handler): void;
81
82
interface Handler {
83
/** Required: Handle code generation requests */
84
onGenerate(options: GeneratorOptions): Promise<any>;
85
/** Optional: Provide generator metadata */
86
onManifest?(config: GeneratorConfig): GeneratorManifest | Promise<GeneratorManifest>;
87
}
88
```
89
90
### Process Management
91
92
Advanced generator process management for scenarios requiring direct control over subprocess communication.
93
94
```typescript { .api }
95
class GeneratorProcess {
96
constructor(pathOrCommand: string, options?: GeneratorProcessOptions);
97
98
/** Initialize the generator process */
99
init(): Promise<void>;
100
/** Get generator manifest information */
101
getManifest(config: GeneratorConfig): Promise<GeneratorManifest | null>;
102
/** Execute code generation */
103
generate(options: GeneratorOptions): Promise<void>;
104
/** Stop the generator process */
105
stop(): void;
106
}
107
108
interface GeneratorProcessOptions {
109
isNode?: boolean;
110
}
111
```
112
113
[Process Management](./process-management.md)
114
115
### Error Handling
116
117
Custom error class for generator-specific failures with support for error codes and additional data.
118
119
```typescript { .api }
120
class GeneratorError extends Error {
121
name: "GeneratorError";
122
123
constructor(
124
message: string,
125
code?: number,
126
data?: any
127
);
128
129
code?: number;
130
data?: any;
131
}
132
```
133
134
## Core Types
135
136
```typescript { .api }
137
interface GeneratorOptions {
138
generator: GeneratorConfig;
139
otherGenerators: GeneratorConfig[];
140
schemaPath: string;
141
dmmf: DMMF.Document;
142
datasources: DataSource[];
143
datamodel: string;
144
version: string;
145
binaryPaths?: BinaryPaths;
146
postinstall?: boolean;
147
noEngine?: boolean;
148
noHints?: boolean;
149
allowNoModels?: boolean;
150
envPaths?: EnvPaths;
151
typedSql?: SqlQueryOutput[];
152
}
153
154
interface GeneratorConfig {
155
name: string;
156
output: EnvValue | null;
157
isCustomOutput?: boolean;
158
provider: EnvValue;
159
config: { [key: string]: string | string[] | undefined };
160
binaryTargets: BinaryTargetsEnvValue[];
161
previewFeatures: string[];
162
envPaths?: EnvPaths;
163
sourceFilePath: string;
164
}
165
166
interface GeneratorManifest {
167
prettyName?: string;
168
defaultOutput?: string;
169
denylists?: {
170
models?: string[];
171
fields?: string[];
172
};
173
requiresGenerators?: string[];
174
requiresEngines?: EngineType[];
175
version?: string;
176
requiresEngineVersion?: string;
177
}
178
179
interface EnvValue {
180
fromEnvVar: null | string;
181
value: null | string;
182
}
183
184
interface BinaryTargetsEnvValue {
185
fromEnvVar: string | null;
186
value: string;
187
native?: boolean;
188
}
189
190
interface DataSource {
191
name: string;
192
provider: ConnectorType;
193
activeProvider: ActiveConnectorType;
194
url: EnvValue;
195
directUrl?: EnvValue;
196
schemas: string[];
197
sourceFilePath: string;
198
}
199
200
type ConnectorType =
201
| "mysql"
202
| "mongodb"
203
| "sqlite"
204
| "postgresql"
205
| "postgres"
206
| "prisma+postgres"
207
| "sqlserver"
208
| "cockroachdb";
209
210
type ActiveConnectorType = Exclude<ConnectorType, "postgres" | "prisma+postgres">;
211
212
type EngineType = "queryEngine" | "libqueryEngine" | "schemaEngine";
213
214
type BinaryPaths = {
215
schemaEngine?: { [binaryTarget: string]: string };
216
queryEngine?: { [binaryTarget: string]: string };
217
libqueryEngine?: { [binaryTarget: string]: string };
218
};
219
220
type EnvPaths = {
221
rootEnvPath: string | null;
222
schemaEnvPath: string | undefined;
223
};
224
225
type SqlQueryOutput = {
226
name: string;
227
source: string;
228
documentation: string | null;
229
parameters: SqlQueryParameterOutput[];
230
resultColumns: SqlQueryColumnOutput[];
231
};
232
233
type SqlQueryParameterOutput = {
234
name: string;
235
typ: QueryIntrospectionType;
236
documentation: string | null;
237
nullable: boolean;
238
};
239
240
type SqlQueryColumnOutput = {
241
name: string;
242
typ: QueryIntrospectionType;
243
nullable: boolean;
244
};
245
246
type QueryIntrospectionType = QueryIntrospectionBuiltinType | (string & {});
247
248
type QueryIntrospectionBuiltinType =
249
| "int" | "bigint" | "float" | "double" | "string" | "enum" | "bytes"
250
| "bool" | "char" | "decimal" | "json" | "xml" | "uuid" | "datetime"
251
| "date" | "time" | "int-array" | "bigint-array" | "float-array"
252
| "double-array" | "string-array" | "char-array" | "bytes-array"
253
| "bool-array" | "decimal-array" | "json-array" | "xml-array"
254
| "uuid-array" | "datetime-array" | "date-array" | "time-array"
255
| "null" | "unknown";
256
```
257
258
## Legacy Exports
259
260
The package includes deprecated re-exports for backwards compatibility:
261
262
```typescript { .api }
263
/** @deprecated Use @prisma/dmmf package directly */
264
type DMMF = typeof import("@prisma/dmmf");
265
266
/** DMMF Document contains the complete Prisma schema structure */
267
namespace DMMF {
268
interface Document {
269
datamodel: Datamodel;
270
schema: Schema;
271
mappings: Mappings;
272
}
273
274
interface Datamodel {
275
models: Model[];
276
enums: DatamodelEnum[];
277
types: Model[];
278
}
279
280
interface Model {
281
name: string;
282
dbName?: string;
283
fields: Field[];
284
primaryKey?: PrimaryKey;
285
uniqueFields: string[][];
286
uniqueIndexes: UniqueIndex[];
287
documentation?: string;
288
}
289
290
interface Field {
291
name: string;
292
kind: FieldKind;
293
isList: boolean;
294
isRequired: boolean;
295
isUnique: boolean;
296
isId: boolean;
297
isReadOnly: boolean;
298
hasDefaultValue: boolean;
299
type: string;
300
documentation?: string;
301
}
302
303
type FieldKind = "scalar" | "object" | "enum" | "unsupported";
304
}
305
306
/** @deprecated Generators shouldn't need JSON-RPC internals */
307
namespace JsonRPC {
308
type Request = {
309
jsonrpc: "2.0";
310
method: string;
311
params?: any;
312
id: number;
313
};
314
315
type Response = SuccessResponse | ErrorResponse;
316
317
type SuccessResponse = {
318
jsonrpc: "2.0";
319
result: any;
320
id: number;
321
};
322
323
type ErrorResponse = {
324
jsonrpc: "2.0";
325
error: {
326
code: number;
327
message: string;
328
data: any;
329
};
330
id: number;
331
};
332
333
function isErrorResponse(response: Response): response is ErrorResponse;
334
}
335
```