8000 fix(zod): avoid importing Prisma enum, recognize enum fields with default by ymc9 · Pull Request #2307 · zenstackhq/zenstack · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 5 additions & 10 deletions packages/schema/src/plugins/zod/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -340,7 +340,7 @@
});
this.sourceFiles.push(sf);
sf.replaceWithText((writer) => {
this.addPreludeAndImports(typeDef, writer, output);
this.addPreludeAndImports(typeDef, writer);

writer.write(`const baseSchema = z.object(`);
writer.inlineBlock(() => {
Expand Down Expand Up @@ -383,7 +383,7 @@
return schemaName;
}

private addPreludeAndImports(decl: DataModel | TypeDef, writer: CodeBlockWriter, output: string) {
private addPreludeAndImports(decl: DataModel | TypeDef, writer: CodeBlockWriter) {
writer.writeLine(`import { z } from 'zod/${this.zodVersion}';`);

// import user-defined enums from Prisma as they might be referenced in the expressions
Expand All @@ -396,10 +396,6 @@
}
}
}
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>();
Expand Down Expand Up @@ -448,7 +444,7 @@
const relations = model.fields.filter((field) => isDataModel(field.type.reference?.ref));
const fkFields = model.fields.filter((field) => isForeignKeyField(field));

this.addPreludeAndImports(model, writer, output);
this.addPreludeAndImports(model, writer);

// base schema - including all scalar fields, with optionality following the schema
this.createModelBaseSchema('baseSchema', writer, scalarFields, true);
Expand Down Expand Up @@ -730,9 +726,7 @@
/**
* Schema refinement function for applying \`@@validate\` rules.
*/
export function ${refineFuncName}<T>(schema: z.ZodType<T>) { return schema${refinements.join(
'\n'
)};
export function ${refineFuncName}<T>(schema: z.ZodType<T>) { return schema${refinements.join('\n')};
}
`
);
Expand Down Expand Up @@ -766,6 +760,7 @@
let expr = new TypeScriptExpressionTransformer({
context: ExpressionContext.ValidationRule,
fieldReferenceContext: 'value',
useLiteralEnum: true,
}).transform(valueArg);

if (isDataModelFieldReference(valueArg)) {
Expand All @@ -774,7 +769,7 @@
expr = `${expr} ?? true`;
}

return `.refine((value: any) => ${expr}${options})`;

Check warning

Code scanning / CodeQL

Improper code sanitization Medium

Code construction depends on an
improperly sanitized value
.
} catch (err) {
if (err instanceof TypeScriptExpressionTransformerError) {
throw new PluginError(name, err.message);
Expand Down
4 changes: 3 additions & 1 deletion packages/schema/src/plugins/zod/utils/schema-gen.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { upperCaseFirst } from '@zenstackhq/runtime/local-helpers';
import { getLiteral, hasAttribute, isFromStdlib } from '@zenstackhq/sdk';
import { getLiteral, hasAttribute, isEnumFieldReference, isFromStdlib } from '@zenstackhq/sdk';
import {
DataModelField,
DataModelFieldAttribute,
Expand Down Expand Up @@ -246,6 +246,8 @@ export function getFieldSchemaDefault(field: DataModelField | TypeDefField) {
return arg.value.value;
} else if (isBooleanLiteral(arg.value)) {
return arg.value.value;
} else if (isEnumFieldReference(arg.value) && arg.value.target.ref) {
return JSON.stringify(arg.value.target.ref.name);
} else if (
isInvocationExpr(arg.value) &&
isFromStdlib(arg.value.function.ref!) &&
Expand Down
5 changes: 4 additions & 1 deletion packages/sdk/src/typescript-expression-transformer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
futureRefContext?: string;
context: ExpressionContext;
operationContext?: 'read' | 'create' | 'update' | 'postUpdate' | 'delete';
useLiteralEnum?: boolean;
};

type Casing = 'original' | 'upper' | 'lower' | 'capitalize' | 'uncapitalize';
Expand Down Expand Up @@ -260,7 +261,7 @@
return this.ensureBooleanTernary(
args[0],
field,
`${this.transform(args[1], normalizeUndefined)}?.every((item) => ${field}?.includes(item))`

Check warning

Code scanning / CodeQL

Improper code sanitization Medium

Code construction depends on an
improperly sanitized value
.
);
}

Expand All @@ -270,7 +271,7 @@
return this.ensureBooleanTernary(
args[0],
field,
`${this.transform(args[1], normalizeUndefined)}?.some((item) => ${field}?.includes(item))`

Check warning

Code scanning / CodeQL

Improper code sanitization Medium

Code construction depends on an
improperly sanitized value
.
);
}

Expand Down Expand Up @@ -392,7 +393,9 @@
}

if (isEnumField(expr.target.ref)) {
return `${expr.target.ref.$container.name}.${expr.target.ref.name}`;
return this.options.useLiteralEnum
? JSON.stringify(expr.target.ref.name)
: `${expr.target.ref.$container.name}.${expr.target.ref.name}`;
} else {
if (this.options?.isPostGuard) {
// if we're processing post-update, any direct field access should be
Expand Down Expand Up @@ -562,9 +565,9 @@
const predicate = innerTransformer.transform(expr.right, normalizeUndefined);

return match(operator)
.with('?', () => this.ensureBoolean(`(${operand})?.some((_item: any) => ${predicate})`))

Check warning

Code scanning / CodeQL

Improper code sanitization Medium

Code construction depends on an
improperly sanitized value
.
.with('!', () => this.ensureBoolean(`(${operand})?.every((_item: any) => ${predicate})`))

Check warning

Code scanning / CodeQL

Improper code sanitization Medium

Code construction depends on an
improperly sanitized value
.
.with('^', () => `!((${operand})?.some((_item: any) => ${predicate}))`)

Check warning

Code scanning / CodeQL

Improper code sanitization Medium

Code construction depends on an
improperly sanitized value
.
.exhaustive();
}
}
23 changes: 23 additions & 0 deletions tests/regression/tests/issue-2291.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { loadSchema } from '@zenstackhq/testtools';

describe('Issue 2291', () => {
it('should work', async () => {
const { zodSchemas } = await loadSchema(
`
enum SomeEnum {
Ex1
Ex2
}

/// Post model
model Post {
id String @id @default(cuid())
e SomeEnum @default(Ex1)
}
`,
{ fullZod: true }
);

expect(zodSchemas.models.PostSchema.parse({ id: '1' })).toEqual({ id: '1', e: 'Ex1' });
});
});
Loading
0