Skip to content
Closed
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
8 changes: 8 additions & 0 deletions packages/orm/src/client/zod/factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1547,6 +1547,14 @@ export class ZodSchemaFactory<
return;
}
const fieldDef = requireField(this.schema, model, field);

if (fieldDef.computed) {
return;
}

if (this.isDelegateDiscriminator(fieldDef)) {
return;
}

if (fieldDef.relation) {
if (skipRelations) {
Expand Down
189 changes: 189 additions & 0 deletions packages/zod/test/factory.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -636,3 +636,192 @@ describe('SchemaFactory - makeEnumSchema', () => {
expect(() => factory.makeEnumSchema('Unknown' as any)).toThrow();
});
});

describe('SchemaFactory - Computed and Discriminator Fields', () => {
// Create a test schema with computed and discriminator fields
const testSchema = {
provider: { type: "sqlite" },
models: {
TestUser: {
name: "TestUser",
fields: {
id: {
name: "id",
type: "String",
id: true,
default: { type: "function", name: "cuid" }
},
name: {
name: "name",
type: "String"
},
postCount: {
name: "postCount",
type: "Int",
computed: true
}
}
},
TestAsset: {
name: "TestAsset",
fields: {
id: {
name: "id",
type: "String",
id: true,
default: { type: "function", name: "cuid" }
},
name: {
name: "name",
type: "String"
},
assetType: {
name: "assetType",
type: "String",
discriminator: true
}
},
delegate: {
discriminator: "assetType"
}
},
TestDocument: {
name: "TestDocument",
fields: {
id: {
name: "id",
type: "String",
id: true,
default: { type: "function", name: "cuid" },
originModel: "TestAsset"
},
name: {
name: "name",
type: "String",
originModel: "TestAsset"
},
assetType: {
name: "assetType",
type: "String",
discriminator: true,
originModel: "TestAsset"
},
fileSize: {
name: "fileSize",
type: "Int"
}
},
extends: "TestAsset",
delegate: {
discriminator: "assetType"
}
}
}
} as any;

const testFactory = createSchemaFactory(testSchema);

describe('computed fields', () => {
it('excludes computed fields from create schema', () => {
const createSchema = testFactory.makeModelCreateSchema('TestUser');
const result = createSchema.safeParse({
id: 'user1',
name: 'Test User',
postCount: 5 // This should be invalid - computed field
});

expect(result.success).toBe(false);
if (!result.success) {
const invalidKeys = result.error.issues.map(issue => issue.path[0]);
expect(invalidKeys).toContain('postCount');
Comment on lines +735 to +736

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

# First, let's look at the test file around the specified lines
wc -l packages/zod/test/factory.test.ts

Repository: zenstackhq/zenstack

Length of output: 100


🏁 Script executed:

# Read the relevant section of the test file
sed -n '730,820p' packages/zod/test/factory.test.ts

Repository: zenstackhq/zenstack

Length of output: 4113


🏁 Script executed:

# Search for unrecognized_keys and issue structure in the test file
rg -n "unrecognized_keys|issue\.keys|issue\.path" packages/zod/test/factory.test.ts -C3

Repository: zenstackhq/zenstack

Length of output: 1347


🏁 Script executed:

# Find the schema factory implementation
fd -e ts "factory" packages/zod --type f

Repository: zenstackhq/zenstack

Length of output: 124


🏁 Script executed:

# Look for makeModelCreateSchema and schema configuration
rg -n "makeModelCreateSchema|makeModelUpdateSchema" packages/zod --type ts -A 5 | head -100

Repository: zenstackhq/zenstack

Length of output: 7865


🏁 Script executed:

# Check the Zod package version to understand its error structure
cat packages/zod/package.json | grep -A 2 -B 2 '"zod"'

Repository: zenstackhq/zenstack

Length of output: 338


🏁 Script executed:

# Look for how the schemas handle unknown fields
rg -n "strict|unknown" packages/zod --type ts -B 2 -A 2 | head -80

Repository: zenstackhq/zenstack

Length of output: 4942


🏁 Script executed:

# Look at the factory.ts implementation for schema creation
sed -n '60,120p' packages/zod/src/factory.ts

Repository: zenstackhq/zenstack

Length of output: 2510


🏁 Script executed:

# Check the test setup to see if there are any logging or debugging of error structures
sed -n '1,100p' packages/zod/test/factory.test.ts

Repository: zenstackhq/zenstack

Length of output: 3874


🏁 Script executed:

# Search for any test output or error logging around these assertions
rg -n "console\.|issue\.|error\." packages/zod/test/factory.test.ts | grep -A 3 -B 3 "postCount\|assetType"

Repository: zenstackhq/zenstack

Length of output: 620


🏁 Script executed:

# Look for the schema definitions being tested (TestUser, TestDocument models)
rg -n "model TestUser|model TestDocument|model TestAsset" packages/zod/test -A 5

Repository: zenstackhq/zenstack

Length of output: 45


🏁 Script executed:

# Search for where test models are defined
rg -n "TestUser\|TestDocument\|TestAsset" packages/zod/test -B 5 -A 5 | head -150

Repository: zenstackhq/zenstack

Length of output: 45


🏁 Script executed:

# Look for the schema file that contains test model definitions
rg -n "model TestUser\|model TestDocument\|model TestAsset" packages/zod

Repository: zenstackhq/zenstack

Length of output: 45


🏁 Script executed:

# Check the test schema file
cat packages/zod/test/schema/schema.ts | head -200

Repository: zenstackhq/zenstack

Length of output: 8600


🏁 Script executed:

# Search for where TestUser is defined in the test file itself
sed -n '600,750p' packages/zod/test/factory.test.ts | head -200

Repository: zenstackhq/zenstack

Length of output: 5707


🏁 Script executed:

# Look for describe blocks or test setup for TestUser/TestDocument
rg -n "describe.*computed\|describe.*discriminator\|TestUser\|TestDocument" packages/zod/test/factory.test.ts -B 10 | head -100

Repository: zenstackhq/zenstack

Length of output: 45


🏁 Script executed:

# Search for any schema setup in the test file
rg -n "beforeEach\|beforeAll\|testFactory\|schema" packages/zod/test/factory.test.ts | head -30

Repository: zenstackhq/zenstack

Length of output: 45


🏁 Script executed:

# Look at the full makeModelCreateSchema implementation to check if computed/discriminator fields are filtered
sed -n '67,90p' packages/zod/src/factory.ts

Repository: zenstackhq/zenstack

Length of output: 1101


🏁 Script executed:

# Check if there's any filtering for computed or discriminator fields in the factory
rg -n "computed|discriminator" packages/zod/src/factory.ts -B 3 -A 3

Repository: zenstackhq/zenstack

Length of output: 45


🏁 Script executed:

# Look for FieldDef interface to understand what properties are available
rg -n "interface FieldDef\|type FieldDef" packages/zod/src -A 20

Repository: zenstackhq/zenstack

Length of output: 45


🏁 Script executed:

# Test what Zod actually reports for unknown keys - create a simple test
cat > /tmp/test_zod_errors.js << 'EOF'
const z = require('zod');

// Test 1: Zod 4.x error structure with strict object
const schema = z.strictObject({
  id: z.string(),
  name: z.string()
});

const result = schema.safeParse({
  id: 'test',
  name: 'Test',
  unknownField: 'extra'
});

if (!result.success) {
  console.log('Error issues:');
  result.error.issues.forEach((issue, i) => {
    console.log(`Issue ${i}:`);
    console.log('  code:', issue.code);
    console.log('  path:', issue.path);
    console.log('  keys:', issue.keys);
    console.log('  message:', issue.message);
  });
}
EOF
node /tmp/test_zod_errors.js

Repository: zenstackhq/zenstack

Length of output: 937


🏁 Script executed:

# Check if computed or discriminator fields should be filtered
rg -n "computed\|discriminator" packages/zod/src -B 5 -A 5

Repository: zenstackhq/zenstack

Length of output: 45


🏁 Script executed:

# Search in the codebase for how computed fields are handled
rg -n "fieldDef.computed\|fieldDef.discriminator" packages/zod/src

Repository: zenstackhq/zenstack

Length of output: 45


🏁 Script executed:

# Look at what properties FieldDef has
find packages/zod/src -name "*.ts" -type f | head -5 | xargs cat | grep -A 30 "FieldDef"

Repository: zenstackhq/zenstack

Length of output: 3169


🏁 Script executed:

# Search for the actual field definition structure
rg -n "interface.*Field\|type.*Field" packages/zod -A 15 | head -100

Repository: zenstackhq/zenstack

Length of output: 45


🏁 Script executed:

# Find FieldDef definition in the schema package
find packages -name "*.ts" -type f | xargs grep -l "interface FieldDef\|type FieldDef" | head -5

Repository: zenstackhq/zenstack

Length of output: 250


🏁 Script executed:

# Check `@zenstackhq/schema` package for FieldDef
find . -path "*/node_modules" -prune -o -name "*.ts" -print | xargs grep -l "export.*interface FieldDef\|export.*type FieldDef" 2>/dev/null | head -5

Repository: zenstackhq/zenstack

Length of output: 94


🏁 Script executed:

# Search for where FieldDef is imported from
rg "from.*schema.*FieldDef" packages/zod/src

Repository: zenstackhq/zenstack

Length of output: 45


🏁 Script executed:

# Look at the schema package structure
ls -la packages/schema/src/ 2>/dev/null || find packages -type d -name "schema" | head -3

Repository: zenstackhq/zenstack

Length of output: 491


🏁 Script executed:

# Look at FieldDef definition in schema.ts
sed -n '1,400p' packages/schema/src/schema.ts | grep -A 30 "interface FieldDef\|type FieldDef"

Repository: zenstackhq/zenstack

Length of output: 859


🏁 Script executed:

# Search for computed and discriminator in the schema file
rg -n "computed\|discriminator" packages/schema/src/schema.ts -B 2 -A 2

Repository: zenstackhq/zenstack

Length of output: 45


🏁 Script executed:

# Get the full FieldDef interface
cat packages/schema/src/schema.ts | sed -n '/interface FieldDef/,/^}/p'

Repository: zenstackhq/zenstack

Length of output: 45


🏁 Script executed:

# Check if computed and discriminator fields are being filtered in the factory
sed -n '67,113p' packages/zod/src/factory.ts

Repository: zenstackhq/zenstack

Length of output: 2030


🏁 Script executed:

# Check makeModelUpdateSchema too
sed -n '92,113p' packages/zod/src/factory.ts

Repository: zenstackhq/zenstack

Length of output: 990


🏁 Script executed:

# Look at the full makeModelCreateSchema and makeModelUpdateSchema implementations
sed -n '40,113p' packages/zod/src/factory.ts

Repository: zenstackhq/zenstack

Length of output: 3273


🏁 Script executed:

# Search for any filtering logic for computed or isDiscriminator fields
rg -n "computed\|isDiscriminator" packages/zod/src/factory.ts

Repository: zenstackhq/zenstack

Length of output: 45


🏁 Script executed:

# Look at what the actual issue structure would be - check test output expectations
rg -n "issue\.code\|issue\.keys\|issue\.path" packages/zod/test/factory.test.ts -B 2 -A 2

Repository: zenstackhq/zenstack

Length of output: 45


🏁 Script executed:

# Check if there's any code that checks for computed or discriminator fields that should be filtering them
rg -n "computed\|isDiscriminator" packages/zod/src -B 3 -A 3

Repository: zenstackhq/zenstack

Length of output: 45


🏁 Script executed:

# Look at the test more carefully - find where testFactory is initialized
sed -n '700,730p' packages/zod/test/factory.test.ts

Repository: zenstackhq/zenstack

Length of output: 1160


🏁 Script executed:

# Check if computed and discriminator fields are actually supposed to be excluded
rg -n "should be excluded\|should be invalid" packages/zod/test/factory.test.ts

Repository: zenstackhq/zenstack

Length of output: 45


🏁 Script executed:

# Let me check if computed and discriminator fields SHOULD be filtered out
# by looking at the type definitions that describe what the create schemas should contain
rg -n "GetModelCreateFieldsShape" packages/zod/src/types.ts -B 5 -A 15

Repository: zenstackhq/zenstack

Length of output: 1000


🏁 Script executed:

# Check what fields should be in create schemas
sed -n '1,150p' packages/zod/src/types.ts

Repository: zenstackhq/zenstack

Length of output: 4646


🏁 Script executed:

# Check if GetModelFields filters out computed or discriminator fields
rg -n "GetModelFields" packages/schema/src -A 5

Repository: zenstackhq/zenstack

Length of output: 6827


🏁 Script executed:

# Look at the schema accessor to understand GetModelFields
sed -n '1,300p' packages/schema/src/accessor.ts | grep -A 20 "GetModelFields"

Repository: zenstackhq/zenstack

Length of output: 45


🏁 Script executed:

# Check the actual implementation of how fields are retrieved
rg -n "getModelFields\|getFields" packages/schema/src -B 2 -A 10

Repository: zenstackhq/zenstack

Length of output: 45


Exclude computed and discriminator fields from create/update schemas, and fix error assertions to check issue.keys instead of issue.path.

The factory code doesn't filter out computed and isDiscriminator fields when building create and update schemas—only relations are excluded. This means computed fields like postCount and discriminator fields like assetType are included in the schemas when they shouldn't be.

Additionally, when these fields are passed during validation, Zod reports them as unrecognized keys via code === 'unrecognized_keys' with keys: string[], not through issue.path. The test assertions checking issue.path[0] will fail because unrecognized keys have empty paths.

Fix both issues:

  1. Add filtering for computed and discriminator fields in makeModelCreateSchema and makeModelUpdateSchema
  2. Update test assertions to check issue.code === 'unrecognized_keys' && issue.keys.includes(fieldName) instead of checking issue.path
Proposed fixes

In packages/zod/src/factory.ts, update the loops to exclude computed and discriminator fields:

for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) {
    if (fieldDef.relation) {
        continue;
    }
+   if (fieldDef.computed || fieldDef.isDiscriminator) {
+       continue;
+   }

In packages/zod/test/factory.test.ts, update error assertions:

-const invalidKeys = result.error.issues.map(issue => issue.path[0]);
-expect(invalidKeys).toContain('postCount');
+const hasPostCountIssue = result.error.issues.some(
+    (issue) => issue.code === 'unrecognized_keys' && issue.keys.includes('postCount')
+);
+expect(hasPostCountIssue).toBe(true);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/zod/test/factory.test.ts` around lines 735 - 736, The create/update
schema builders are still including computed and discriminator fields; update
makeModelCreateSchema and makeModelUpdateSchema to filter out fields where
field.computed === true or field.isDiscriminator === true (in the same way
relations are excluded) so computed/discriminator fields like postCount and
assetType are not part of the generated schemas. Also adjust the test assertions
in factory.test.ts: instead of reading invalid keys from issue.path, assert
unrecognized-key issues by checking issue.code === 'unrecognized_keys' and that
issue.keys.includes('postCount') / issue.keys.includes('assetType') (i.e., map
result.error.issues to their .keys for these checks).

}
});

it('excludes computed fields from update schema', () => {
const updateSchema = testFactory.makeModelUpdateSchema('TestUser');
const result = updateSchema.safeParse({
name: 'Updated User',
postCount: 10 // This should be invalid - computed field
});

expect(result.success).toBe(false);
if (!result.success) {
const invalidKeys = result.error.issues.flatMap(issue =>
issue.path.filter(p => p === 'postCount')
);
expect(invalidKeys.length).toBeGreaterThan(0);
}
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

});

describe('discriminator fields', () => {
it('excludes discriminator fields from create schema', () => {
const createSchema = testFactory.makeModelCreateSchema('TestDocument');
const result = createSchema.safeParse({
id: 'doc1',
name: 'Test Document',
assetType: 'document', // This should be invalid - discriminator field
fileSize: 1024
});

expect(result.success).toBe(false);
if (!result.success) {
const invalidKeys = result.error.issues.map(issue => issue.path[0]);
expect(invalidKeys).toContain('assetType');
}
});

it('excludes discriminator fields from update schema', () => {
const updateSchema = testFactory.makeModelUpdateSchema('TestDocument');
const result = updateSchema.safeParse({
name: 'Updated Document',
assetType: 'document', // This should be invalid - discriminator field
fileSize: 2048
});

expect(result.success).toBe(false);
if (!result.success) {
const invalidKeys = result.error.issues.flatMap(issue =>
issue.path.filter(p => p === 'assetType')
);
expect(invalidKeys.length).toBeGreaterThan(0);
}
});

});

describe('base model with discriminator', () => {
it('excludes discriminator fields from base model schemas', () => {
const createSchema = testFactory.makeModelCreateSchema('TestAsset');
const updateSchema = testFactory.makeModelUpdateSchema('TestAsset');

// Test create schema
const createResult = createSchema.safeParse({
id: 'asset1',
name: 'Test Asset',
assetType: 'generic' // Should be invalid
});
expect(createResult.success).toBe(false);

// Test update schema
const updateResult = updateSchema.safeParse({
name: 'Updated Asset',
assetType: 'generic' // Should be invalid
});
expect(updateResult.success).toBe(false);

// Valid data should work
const validCreateResult = createSchema.safeParse({
id: 'asset1',
name: 'Test Asset'
});
expect(validCreateResult.success).toBe(true);

const validUpdateResult = updateSchema.safeParse({
name: 'Updated Asset'
});
expect(validUpdateResult.success).toBe(true);
});
});
});
Loading