-
-
Notifications
You must be signed in to change notification settings - Fork 144
Expand file tree
/
Copy pathgenerator.ts
More file actions
829 lines (731 loc) · 31.6 KB
/
generator.ts
File metadata and controls
829 lines (731 loc) · 31.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
import { DELEGATE_AUX_RELATION_PREFIX } from '@zenstackhq/runtime';
import { upperCaseFirst } from '@zenstackhq/runtime/local-helpers';
import {
ExpressionContext,
PluginError,
PluginGlobalOptions,
PluginOptions,
RUNTIME_PACKAGE,
TypeScriptExpressionTransformer,
TypeScriptExpressionTransformerError,
ensureEmptyDir,
getAttributeArg,
getAttributeArgLiteral,
getDataModels,
getLiteralArray,
hasAttribute,
isDataModelFieldReference,
isDiscriminatorField,
isEnumFieldReference,
isForeignKeyField,
isFromStdlib,
isIdField,
parseOptionAsStrings,
resolvePath,
saveSourceFile,
} from '@zenstackhq/sdk';
import {
DataModel,
DataModelField,
EnumField,
Model,
TypeDef,
isArrayExpr,
isDataModel,
isEnum,
isTypeDef,
} from '@zenstackhq/sdk/ast';
import { addMissingInputObjectTypes, resolveAggregateOperationSupport } from '@zenstackhq/sdk/dmmf-helpers';
import { getPrismaClientImportSpec, supportCreateMany, type DMMF } from '@zenstackhq/sdk/prisma';
import { streamAllContents } from 'langium';
import path from 'path';
import type { CodeBlockWriter, SourceFile } from 'ts-morph';
import { name } from '.';
import { getDefaultOutputFolder } from '../plugin-utils';
import Transformer from './transformer';
import { ObjectMode } from './types';
import { makeFieldSchema } from './utils/schema-gen';
export class ZodSchemaGenerator {
private readonly sourceFiles: SourceFile[] = [];
private readonly globalOptions: PluginGlobalOptions;
private readonly mode: ObjectMode;
private readonly zodVersion: 'v3' | 'v4' = 'v3';
constructor(
private readonly model: Model,
private readonly options: PluginOptions,
private readonly dmmf: DMMF.Document,
globalOptions: PluginGlobalOptions | undefined
) {
if (!globalOptions) {
throw new Error('Global options are required');
}
this.globalOptions = globalOptions;
// options validation
if (
this.options.mode &&
(typeof this.options.mode !== 'string' || !['strip', 'strict', 'passthrough'].includes(this.options.mode))
) {
throw new PluginError(
name,
`Invalid mode option: "${this.options.mode}". Must be one of 'strip', 'strict', or 'passthrough'.`
);
}
this.mode = (this.options.mode ?? 'strict') as ObjectMode;
if (this.options.version) {
if (typeof this.options.version !== 'string' || !['v3', 'v4'].includes(this.options.version)) {
throw new PluginError(
name,
`Invalid "version" option: "${this.options.version}". Must be one of 'v3' or 'v4'.`
);
}
this.zodVersion = this.options.version as 'v3' | 'v4';
}
}
async generate() {
let output = this.options.output as string;
if (!output) {
const defaultOutputFolder = getDefaultOutputFolder(this.globalOptions);
if (defaultOutputFolder) {
output = path.join(defaultOutputFolder, 'zod');
} else {
output = './generated/zod';
}
}
output = resolvePath(output, this.options);
ensureEmptyDir(output);
Transformer.setOutputPath(output);
// calculate the models to be excluded
const excludeModels = this.getExcludedModels();
const prismaClientDmmf = this.dmmf;
const modelOperations = prismaClientDmmf.mappings.modelOperations.filter(
(o) => !excludeModels.find((e) => e === o.model)
);
const inputObjectTypes = (prismaClientDmmf.schema.inputObjectTypes.prisma ?? []).filter(
(type) =>
!excludeModels.some((e) => type.name.toLowerCase().startsWith(e.toLocaleLowerCase())) &&
// exclude delegate aux related types
!type.name.toLowerCase().includes(DELEGATE_AUX_RELATION_PREFIX)
);
const outputObjectTypes = prismaClientDmmf.schema.outputObjectTypes.prisma.filter(
(type) =>
!excludeModels.some((e) => type.name.toLowerCase().startsWith(e.toLowerCase())) &&
// exclude delegate aux related types
!type.name.toLowerCase().includes(DELEGATE_AUX_RELATION_PREFIX)
);
const models: DMMF.Model[] = prismaClientDmmf.datamodel.models.filter(
(m) => !excludeModels.find((e) => e === m.name)
);
// common schemas
await this.generateCommonSchemas(output);
// enums
await this.generateEnumSchemas(
prismaClientDmmf.schema.enumTypes.prisma,
prismaClientDmmf.schema.enumTypes.model ?? []
);
await this.generateModelSchemas(output, excludeModels);
if (this.options.modelOnly) {
// generate stub for object and input schemas, so the exports from '@zenstackhq/runtime/zod' are available
this.sourceFiles.push(
this.project.createSourceFile(path.join(output, 'objects', 'index.ts'), '', { overwrite: true })
);
this.sourceFiles.push(
this.project.createSourceFile(path.join(output, 'input', 'index.ts'), '', { overwrite: true })
);
} else {
// detailed object schemas referenced from input schemas
addMissingInputObjectTypes(inputObjectTypes, outputObjectTypes, models);
const aggregateOperationSupport = resolveAggregateOperationSupport(inputObjectTypes);
await this.generateObjectSchemas(inputObjectTypes, output);
// input schemas
const transformer = new Transformer({
models,
modelOperations,
aggregateOperationSupport,
project: this.project,
inputObjectTypes,
zmodel: this.model,
mode: this.mode,
zodVersion: this.zodVersion,
});
await transformer.generateInputSchemas(this.options, this.model);
this.sourceFiles.push(...transformer.sourceFiles);
}
// create barrel file
const exports = [`export * as models from './models'`, `export * as enums from './enums'`];
if (this.options.modelOnly !== true) {
exports.push(`export * as input from './input'`, `export * as objects from './objects'`);
}
this.sourceFiles.push(
this.project.createSourceFile(path.join(output, 'index.ts'), exports.join(';\n'), { overwrite: true })
);
if (this.options.preserveTsFiles === true || this.options.output) {
// if preserveTsFiles is true or the user provided a custom output directory,
// save the generated files
this.sourceFiles.forEach(saveSourceFile);
}
}
private get project() {
return this.globalOptions.tsProject;
}
private getExcludedModels() {
// resolve "generateModels" option
const generateModels = parseOptionAsStrings(this.options, 'generateModels', name);
if (generateModels) {
if (this.options.modelOnly === true) {
// no model reference needs to be considered, directly exclude any model not included
return this.model.declarations
.filter((d) => isDataModel(d) && !generateModels.includes(d.name))
.map((m) => m.name);
} else {
// calculate a transitive closure of models to be included
const todo = getDataModels(this.model).filter((dm) => generateModels.includes(dm.name));
const included = new Set<DataModel>();
while (todo.length > 0) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const dm = todo.pop()!;
included.add(dm);
// add referenced models to the todo list
dm.fields
.map((f) => f.type.reference?.ref)
.filter((type): type is DataModel => isDataModel(type))
.forEach((type) => {
if (!included.has(type)) {
todo.push(type);
}
});
}
// finally find the models to be excluded
return getDataModels(this.model)
.filter((dm) => !included.has(dm))
.map((m) => m.name);
}
} else {
return [];
}
}
private async generateCommonSchemas(output: string) {
// Decimal
this.sourceFiles.push(
this.project.createSourceFile(
path.join(output, 'common', 'index.ts'),
`
import { z } from 'zod/${this.zodVersion}';
export const DecimalSchema = z.any().refine((val) => {
if (typeof val === 'string' || typeof val === 'number') {
return true;
}
// Decimal.js shape
if (typeof val === 'object' && val && Array.isArray(val.d) && typeof val.e === 'number' && typeof val.s === 'number') {
return true;
}
return false;
}, { message: 'Not a valid Decimal value'});
`,
{ overwrite: true }
)
);
}
private async generateEnumSchemas(
prismaSchemaEnum: readonly DMMF.SchemaEnum[],
modelSchemaEnum: readonly DMMF.SchemaEnum[]
) {
const enumTypes = [...prismaSchemaEnum, ...modelSchemaEnum];
const enumNames = enumTypes.map((enumItem) => upperCaseFirst(enumItem.name));
Transformer.enumNames = enumNames ?? [];
const transformer = new Transformer({
enumTypes,
project: this.project,
inputObjectTypes: [],
zmodel: this.model,
mode: this.mode,
zodVersion: this.zodVersion,
});
await transformer.generateEnumSchemas();
this.sourceFiles.push(...transformer.sourceFiles);
}
private async generateObjectSchemas(inputObjectTypes: DMMF.InputType[], output: string) {
// whether Prisma's Unchecked* series of input types should be generated
const generateUnchecked = this.options.noUncheckedInput !== true;
const moduleNames: string[] = [];
for (let i = 0; i < inputObjectTypes.length; i += 1) {
// exclude delegate aux fields
const fields = inputObjectTypes[i]?.fields?.filter((f) => !f.name.includes(DELEGATE_AUX_RELATION_PREFIX));
const name = inputObjectTypes[i]?.name;
if (!generateUnchecked && name.includes('Unchecked')) {
continue;
}
if (name.includes('CreateMany') && !supportCreateMany(this.model)) {
continue;
}
const transformer = new Transformer({
name,
fields,
project: this.project,
inputObjectTypes,
zmodel: this.model,
mode: this.mode,
zodVersion: this.zodVersion,
});
const moduleName = transformer.generateObjectSchema(generateUnchecked, this.options);
moduleNames.push(moduleName);
this.sourceFiles.push(...transformer.sourceFiles);
}
this.sourceFiles.push(
this.project.createSourceFile(
path.join(output, 'objects/index.ts'),
moduleNames.map((name) => `export * from './${name}';`).join('\n'),
{ overwrite: true }
)
);
}
private async generateModelSchemas(output: string, excludedModels: string[]) {
const schemaNames: string[] = [];
for (const dm of getDataModels(this.model)) {
if (!excludedModels.includes(dm.name)) {
schemaNames.push(await this.generateModelSchema(dm, output));
}
}
for (const typeDef of this.model.declarations.filter(isTypeDef)) {
if (!excludedModels.includes(typeDef.name)) {
schemaNames.push(await this.generateTypeDefSchema(typeDef, output));
}
}
this.sourceFiles.push(
this.project.createSourceFile(
path.join(output, 'models', 'index.ts'),
schemaNames.map((name) => `export * from './${name}';`).join('\n'),
{ overwrite: true }
)
);
}
private generateTypeDefSchema(typeDef: TypeDef, output: string) {
const schemaName = `${upperCaseFirst(typeDef.name)}.schema`;
const sf = this.project.createSourceFile(path.join(output, 'models', `${schemaName}.ts`), undefined, {
overwrite: true,
});
this.sourceFiles.push(sf);
sf.replaceWithText((writer) => {
this.addPreludeAndImports(typeDef, writer, output);
writer.write(`const baseSchema = z.object(`);
writer.inlineBlock(() => {
typeDef.fields.forEach((field) => {
writer.writeLine(`${field.name}: ${makeFieldSchema(field)},`);
});
});
switch (this.options.mode) {
case 'strip':
// zod strips by default
writer.writeLine(')');
break;
case 'passthrough':
writer.writeLine(').passthrough();');
break;
default:
writer.writeLine(').strict();');
break;
}
// compile "@@validate" to a function calling zod's `.refine()`
const refineFuncName = this.createRefineFunction(typeDef, writer);
if (refineFuncName) {
// export a schema without refinement for extensibility: `[Model]WithoutRefineSchema`
const noRefineSchema = `${upperCaseFirst(typeDef.name)}WithoutRefineSchema`;
writer.writeLine(`
/**
* \`${typeDef.name}\` schema prior to calling \`.refine()\` for extensibility.
*/
export const ${noRefineSchema} = baseSchema;
export const ${typeDef.name}Schema = ${refineFuncName}(${noRefineSchema});
`);
} else {
writer.writeLine(`export const ${typeDef.name}Schema = baseSchema;`);
}
});
return schemaName;
}
private addPreludeAndImports(decl: DataModel | TypeDef, writer: CodeBlockWriter, output: string) {
writer.writeLine(`import { z } from 'zod/${this.zodVersion}';`);
// import user-defined enums from Prisma as they might be referenced in the expressions
const importEnums = new Set<string>();
for (const node of streamAllContents(decl)) {
if (isEnumFieldReference(node)) {
const field = node.target.ref as EnumField;
if (!isFromStdlib(field.$container)) {
importEnums.add(field.$container.name);
}
}
}
if (importEnums.size > 0) {
const prismaImport = computePrismaClientImport(path.join(output, 'models'), this.options);
writer.writeLine(`import { ${[...importEnums].join(', ')} } from '${prismaImport}';`);
}
// import enum schemas
const importedEnumSchemas = new Set<string>();
for (const field of decl.fields) {
if (field.type.reference?.ref && isEnum(field.type.reference?.ref)) {
const name = upperCaseFirst(field.type.reference?.ref.name);
if (!importedEnumSchemas.has(name)) {
writer.writeLine(`import { ${name}Schema } from '../enums/${name}.schema';`);
importedEnumSchemas.add(name);
}
}
}
// import Decimal
if (decl.fields.some((field) => field.type.type === 'Decimal')) {
writer.writeLine(`import { DecimalSchema } from '../common';`);
writer.writeLine(`import { Decimal } from 'decimal.js';`);
}
// import referenced types' schemas
const referencedTypes = new Set(
decl.fields
.filter((field) => isTypeDef(field.type.reference?.ref) && field.type.reference?.ref.name !== decl.name)
.map((field) => field.type.reference!.ref!.name)
);
for (const refType of referencedTypes) {
writer.writeLine(`import { ${upperCaseFirst(refType)}Schema } from './${upperCaseFirst(refType)}.schema';`);
}
}
private async generateModelSchema(model: DataModel, output: string) {
const schemaName = `${upperCaseFirst(model.name)}.schema`;
const sf = this.project.createSourceFile(path.join(output, 'models', `${schemaName}.ts`), undefined, {
overwrite: true,
});
this.sourceFiles.push(sf);
sf.replaceWithText((writer) => {
const scalarFields = model.fields.filter(
(field) =>
// id fields are always included
isIdField(field) ||
// regular fields only
(!isDataModel(field.type.reference?.ref) && !isForeignKeyField(field))
);
const relations = model.fields.filter((field) => isDataModel(field.type.reference?.ref));
const fkFields = model.fields.filter((field) => isForeignKeyField(field));
this.addPreludeAndImports(model, writer, output);
// base schema - including all scalar fields, with optionality following the schema
this.createModelBaseSchema('baseSchema', writer, scalarFields, true);
// base schema without field defaults
this.createModelBaseSchema('baseSchemaWithoutDefaults', writer, scalarFields, false);
// relation fields
let relationSchema: string | undefined;
let fkSchema: string | undefined;
if (relations.length > 0) {
relationSchema = 'relationSchema';
writer.write(`const ${relationSchema} = z.object(`);
writer.inlineBlock(() => {
[...relations].forEach((field) => {
writer.writeLine(`${field.name}: ${makeFieldSchema(field)},`);
});
});
writer.writeLine(');');
}
if (fkFields.length > 0) {
fkSchema = 'fkSchema';
writer.write(`const ${fkSchema} = z.object(`);
writer.inlineBlock(() => {
fkFields.forEach((field) => {
writer.writeLine(`${field.name}: ${makeFieldSchema(field)},`);
});
});
writer.writeLine(');');
}
// compile "@@validate" to ".refine"
const refineFuncName = this.createRefineFunction(model, writer);
// delegate discriminator fields are to be excluded from mutation schemas
const delegateDiscriminatorFields = model.fields.filter((field) => isDiscriminatorField(field));
const omitDiscriminators =
delegateDiscriminatorFields.length > 0
? `.omit({ ${delegateDiscriminatorFields.map((f) => `${f.name}: true`).join(', ')} })`
: '';
////////////////////////////////////////////////
// 1. Model schema
////////////////////////////////////////////////
let modelSchema = 'baseSchema';
// omit fields
const fieldsToOmit = scalarFields.filter((field) => hasAttribute(field, '@omit'));
if (fieldsToOmit.length > 0) {
modelSchema = this.makeOmit(
modelSchema,
fieldsToOmit.map((f) => f.name)
);
}
// export schema with only scalar fields: `[Model]ScalarSchema`
const modelScalarSchema = `${upperCaseFirst(model.name)}ScalarSchema`;
writer.writeLine(`
/**
* \`${model.name}\` schema excluding foreign keys and relations.
*/
export const ${modelScalarSchema} = ${modelSchema};
`);
modelSchema = modelScalarSchema;
// merge fk fields
if (fkSchema) {
modelSchema = this.makeMerge(modelSchema, fkSchema);
}
// merge relation fields (all optional)
if (relationSchema) {
modelSchema = this.makeMerge(modelSchema, this.makePartial(relationSchema));
}
// refine
if (refineFuncName) {
// export a schema without refinement for extensibility: `[Model]WithoutRefineSchema`
const noRefineSchema = `${upperCaseFirst(model.name)}WithoutRefineSchema`;
writer.writeLine(`
/**
* \`${model.name}\` schema prior to calling \`.refine()\` for extensibility.
*/
export const ${noRefineSchema} = ${modelSchema};
`);
modelSchema = `${refineFuncName}(${noRefineSchema})`;
}
// export the final model schema: `[Model]Schema`
writer.writeLine(`
/**
* \`${model.name}\` schema including all fields (scalar, foreign key, and relations) and validations.
*/
export const ${upperCaseFirst(model.name)}Schema = ${modelSchema};
`);
////////////////////////////////////////////////
// 2. Prisma create & update
////////////////////////////////////////////////
// schema for validating prisma create input (all fields optional)
let prismaCreateSchema = this.makePassthrough(
this.makePartial(`baseSchemaWithoutDefaults${omitDiscriminators}`)
);
if (refineFuncName) {
prismaCreateSchema = `${refineFuncName}(${prismaCreateSchema})`;
}
writer.writeLine(`
/**
* Schema used for validating Prisma create input. For internal use only.
* @private
*/
export const ${upperCaseFirst(model.name)}PrismaCreateSchema = ${prismaCreateSchema};
`);
// schema for validating prisma update input (all fields optional)
// note numeric fields can be simple update or atomic operations
let prismaUpdateSchema = `z.object({
${scalarFields
.filter((f) => !isDiscriminatorField(f))
.map((field) => {
let fieldSchema = makeFieldSchema(field, false);
if (field.type.type === 'Int' || field.type.type === 'Float') {
fieldSchema = `z.union([${fieldSchema}, z.record(z.string(), z.unknown())])`;
}
return `\t${field.name}: ${fieldSchema}`;
})
.join(',\n')}
})`;
prismaUpdateSchema = this.makePassthrough(this.makePartial(prismaUpdateSchema));
writer.writeLine(
`
/**
* Schema used for validating Prisma update input. For internal use only.
* @private
*/
export const ${upperCaseFirst(model.name)}PrismaUpdateSchema = ${prismaUpdateSchema};
`
);
////////////////////////////////////////////////
// 3. Create schema
////////////////////////////////////////////////
let createSchema = `baseSchemaWithoutDefaults${omitDiscriminators}`;
const fieldsWithDefault = scalarFields.filter(
(field) => hasAttribute(field, '@default') || hasAttribute(field, '@updatedAt') || field.type.array
);
// mark fields with default as optional
if (fieldsWithDefault.length > 0) {
// delegate discriminator fields are omitted from the base schema, so we need
// to take care not to make them partial otherwise the schema won't compile
createSchema = this.makePartial(
createSchema,
fieldsWithDefault.filter((f) => !delegateDiscriminatorFields.includes(f)).map((f) => f.name)
);
}
// export schema with only scalar fields: `[Model]CreateScalarSchema`
const createScalarSchema = `${upperCaseFirst(model.name)}CreateScalarSchema`;
writer.writeLine(`
/**
* \`${model.name}\` schema for create operations excluding foreign keys and relations.
*/
export const ${createScalarSchema} = ${createSchema};
`);
if (fkSchema) {
// merge fk fields
createSchema = this.makeMerge(createScalarSchema, fkSchema);
}
if (refineFuncName) {
// export a schema without refinement for extensibility: `[Model]CreateWithoutRefineSchema`
const noRefineSchema = `${upperCaseFirst(model.name)}CreateWithoutRefineSchema`;
writer.writeLine(`
/**
* \`${model.name}\` schema for create operations prior to calling \`.refine()\` for extensibility.
*/
export const ${noRefineSchema} = ${createSchema};
`);
createSchema = `${refineFuncName}(${noRefineSchema})`;
}
// export the final create schema: `[Model]CreateSchema`
writer.writeLine(`
/**
* \`${model.name}\` schema for create operations including scalar fields, foreign key fields, and validations.
*/
export const ${upperCaseFirst(model.name)}CreateSchema = ${createSchema};
`);
////////////////////////////////////////////////
// 3. Update schema
////////////////////////////////////////////////
// for update all fields are optional
let updateSchema = this.makePartial(`baseSchemaWithoutDefaults${omitDiscriminators}`);
// export schema with only scalar fields: `[Model]UpdateScalarSchema`
const updateScalarSchema = `${upperCaseFirst(model.name)}UpdateScalarSchema`;
writer.writeLine(`
/**
* \`${model.name}\` schema for update operations excluding foreign keys and relations.
*/
export const ${updateScalarSchema} = ${updateSchema};
`);
updateSchema = updateScalarSchema;
if (fkSchema) {
// merge fk fields
updateSchema = this.makeMerge(updateSchema, this.makePartial(fkSchema));
}
if (refineFuncName) {
// export a schema without refinement for extensibility: `[Model]UpdateWithoutRefineSchema`
const noRefineSchema = `${upperCaseFirst(model.name)}UpdateWithoutRefineSchema`;
writer.writeLine(`
/**
* \`${model.name}\` schema for update operations prior to calling \`.refine()\` for extensibility.
*/
export const ${noRefineSchema} = ${updateSchema};
`);
updateSchema = `${refineFuncName}(${noRefineSchema})`;
}
// export the final update schema: `[Model]UpdateSchema`
writer.writeLine(`
/**
* \`${model.name}\` schema for update operations including scalar fields, foreign key fields, and validations.
*/
export const ${upperCaseFirst(model.name)}UpdateSchema = ${updateSchema};
`);
});
return schemaName;
}
private createModelBaseSchema(
name: string,
writer: CodeBlockWriter,
scalarFields: DataModelField[],
addDefaults: boolean
) {
writer.write(`const ${name} = z.object(`);
writer.inlineBlock(() => {
scalarFields.forEach((field) => {
writer.writeLine(`${field.name}: ${makeFieldSchema(field, addDefaults)},`);
});
});
switch (this.options.mode) {
case 'strip':
// zod strips by default
writer.writeLine(')');
break;
case 'passthrough':
writer.writeLine(').passthrough();');
break;
default:
writer.writeLine(').strict();');
break;
}
}
private createRefineFunction(decl: DataModel | TypeDef, writer: CodeBlockWriter) {
const refinements = this.makeValidationRefinements(decl);
let refineFuncName: string | undefined;
if (refinements.length > 0) {
refineFuncName = `refine${upperCaseFirst(decl.name)}`;
writer.writeLine(
`
/**
* Schema refinement function for applying \`@@validate\` rules.
*/
export function ${refineFuncName}<T>(schema: z.ZodType<T>) { return schema${refinements.join(
'\n'
)};
}
`
);
return refineFuncName;
} else {
return undefined;
}
}
private makeValidationRefinements(decl: DataModel | TypeDef) {
const attrs = decl.attributes.filter((attr) => attr.decl.ref?.name === '@@validate');
const refinements = attrs
.map((attr) => {
const valueArg = getAttributeArg(attr, 'value');
if (!valueArg) {
return undefined;
}
const messageArg = getAttributeArgLiteral<string>(attr, 'message');
const message = messageArg ? `message: ${JSON.stringify(messageArg)},` : '';
const pathArg = getAttributeArg(attr, 'path');
const path =
pathArg && isArrayExpr(pathArg)
? `path: ['${getLiteralArray<string>(pathArg)?.join(`', '`)}'],`
: '';
const options = `, { ${message} ${path} }`;
try {
let expr = new TypeScriptExpressionTransformer({
context: ExpressionContext.ValidationRule,
fieldReferenceContext: 'value',
}).transform(valueArg);
if (isDataModelFieldReference(valueArg)) {
// if the expression is a simple field reference, treat undefined
// as true since the all fields are optional in validation context
expr = `${expr} ?? true`;
}
return `.refine((value: any) => ${expr}${options})`;
} catch (err) {
if (err instanceof TypeScriptExpressionTransformerError) {
throw new PluginError(name, err.message);
} else {
throw err;
}
}
})
.filter((r) => !!r);
return refinements;
}
private makePartial(schema: string, fields?: string[]) {
if (fields) {
if (fields.length === 0) {
return schema;
} else {
return `${schema}.partial({
${fields.map((f) => `${f}: true`).join(', ')}
})`;
}
} else {
return `${schema}.partial()`;
}
}
private makeOmit(schema: string, fields: string[]) {
return `${schema}.omit({
${fields.map((f) => `${f}: true`).join(', ')},
})`;
}
private makeMerge(schema1: string, schema2: string): string {
return `${schema1}.merge(${schema2})`;
}
private makePassthrough(schema: string) {
return `${schema}.passthrough()`;
}
}
export function computePrismaClientImport(importingFrom: string, options: PluginOptions) {
let importPath = getPrismaClientImportSpec(importingFrom, options);
if (importPath.startsWith(RUNTIME_PACKAGE) && !options.output) {
// default import from `@zenstackhq/runtime` and this plugin is generating
// into default location, we should correct the prisma client import into a
// importing from `.zenstack` to avoid cyclic dependencies with runtime
importPath = importPath.replace(RUNTIME_PACKAGE, '.zenstack');
}
return importPath;
}