Skip to content

fix(zmodel): improve attribute argument assignability check#588

Merged
ymc9 merged 4 commits intodevfrom
fix/issue-584
Jan 11, 2026
Merged

fix(zmodel): improve attribute argument assignability check#588
ymc9 merged 4 commits intodevfrom
fix/issue-584

Conversation

@ymc9
Copy link
Member

@ymc9 ymc9 commented Jan 11, 2026

fixes #584

Summary by CodeRabbit

  • Bug Fixes

    • More precise validation and user-facing error messages for JSON default values, arrays vs. strings, and invalid attribute arguments.
    • Correct handling of explicit null defaults so null literal defaults are recognized and processed.
  • Tests

    • Added regression tests covering JSON default validation for single and array JSON fields across multiple cases (null, plain strings, JSON strings, objects, arrays).

✏️ Tip: You can customize this high-level summary in your review settings.

Copilot AI review requested due to automatic review settings January 11, 2026 07:56
@coderabbitai
Copy link

coderabbitai bot commented Jan 11, 2026

📝 Walkthrough

Walkthrough

Validator return types were changed to a discriminated union with detailed error messages; JSON/@default validation was hardened. A regression test for JSON and JSON[] defaults was added. SDK default-mapping now explicitly handles null defaults and updates related signatures.

Changes

Cohort / File(s) Summary
Validator Logic
packages/language/src/validators/attribute-application-validator.ts
assignableToAttributeParam now returns `{ result: true }
Regression tests
tests/regression/test/issue-584.test.ts
New Vitest cases validating JSON and Json[] @default values (including null, plain string, JSON string literal, JSON array), asserting precise acceptance/rejection behaviors.
SDK default mapping
packages/sdk/src/ts-schema-generator.ts
Explicit null handling for defaults: getFieldMappedDefault and getMappedValue now return null for null literals and signatures updated to include null. Error message adjusted to “Unsupported expression type: …”.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

🐰 I nibbled through defaults and sniffed each JSON seam,
Turned silent booleans into messages that gleam.
Nulls found a home, arrays got their name,
Tests stand watch now, keeping errors tame.
Hop, clap, and cheer — validation’s a clean dream! 🎉

🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title 'fix(zmodel): improve attribute argument assignability check' accurately describes the main code change in the validator, which enhances assignability checking with detailed error messages.
Linked Issues check ✅ Passed The PR addresses issue #584 by improving JSON default value validation to provide specific error messages for invalid defaults on nullable JSON fields.
Out of Scope Changes check ✅ Passed All changes are scoped to JSON default value validation improvements: validator enhancements for attribute arguments, regression test coverage, and schema generator null handling updates.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@claude
Copy link

claude bot commented Jan 11, 2026

Claude finished @ymc9's task —— View job


Code Review Complete ✅

Reviewed PR that fixes issue #584 - improving attribute argument assignability check.

Todo List:

  • Read and analyze changed files
  • Review code quality and best practices
  • Check for potential bugs or issues
  • Evaluate performance considerations
  • Assess security concerns
  • Review test coverage
  • Provide comprehensive feedback

Code Quality & Best Practices ✅

Excellent improvements overall! The refactor significantly enhances error reporting and maintainability:

  1. Better Error Messaging: Changed from generic "Value is not assignable to parameter" to specific, actionable error messages like "expected a JSON string literal", "expected an array of field references", etc.

  2. Clean Return Type: The discriminated union return type {result: true} | {result: false; error: string} is much cleaner than the previous boolean return with side effects.

  3. Consistent Error Handling: All error paths now return descriptive messages, making debugging much easier for users.

JSON Default Value Validation 🎯

The core improvement correctly addresses JSON field default validation:

Before (packages/language/src/validators/attribute-application-validator.ts:418-421):

const dstIsTypedJson = hasAttribute(attr.$container, '@json');
if (dstIsTypedJson && attr.decl.ref?.name === '@default') {
    return argResolvedType.decl === 'String';
}

After (packages/language/src/validators/attribute-application-validator.ts:420-430):

const dstIsJson = attr.$container.type.type === 'Json' || hasAttribute(attr.$container, '@json');
if (dstIsJson && attr.decl.ref?.name === '@default') {
    if (isLiteralJsonString(arg.value)) {
        return success;
    } else {
        return {
            result: false,
            error: 'expected a JSON string literal',
        };
    }
}

✅ Key Improvements:

  • Now validates both Json field type AND @json attribute (was missing Json type check)
  • Actually validates that the string contains valid JSON using isLiteralJsonString() helper
  • Provides clear error message instead of generic failure

Test Coverage ✅

The test suite in tests/regression/test/issue-584.test.ts:5-65 is comprehensive:

  • ✅ Tests invalid cases: null literal and plain string 'hello'
  • ✅ Tests valid cases: JSON string '"hello"', JSON array '[{"hello":1}]', JSON null 'null'
  • ✅ Uses realistic ZModel schemas with proper field definitions
  • ✅ Uses createTestClient() to validate end-to-end behavior

Minor Suggestions

  1. Helper Function Location (packages/language/src/validators/attribute-application-validator.ts:607-617): The isLiteralJsonString() helper is well-implemented with proper error handling, but consider moving to a shared utilities module if JSON validation is needed elsewhere.

  2. Error Message Formatting (packages/language/src/validators/attribute-application-validator.ts:453-455): There's a formatting issue with extra whitespace:

error: `
                    expected ${dstIsArray ? 'array' : 'non-array'}`,

Should be:

error: `expected ${dstIsArray ? 'array' : 'non-array'}`,
  1. Array Logic Improvement (packages/language/src/validators/attribute-application-validator.ts:466): Good change from find() to some() for better semantic clarity when checking if any items are invalid.

Security & Performance ✅

  • Security: The JSON.parse() call in isLiteralJsonString() is safely wrapped in try-catch
  • Performance: Changes are minimal and don't introduce any performance concerns
  • Memory: No memory leaks or unnecessary object allocations

Overall Assessment 🎉

This is a high-quality fix that:

  • ✅ Addresses the root issue comprehensively
  • ✅ Significantly improves developer experience with better error messages
  • ✅ Maintains backward compatibility
  • ✅ Includes thorough test coverage
  • ✅ Follows existing code patterns and conventions

Recommendation: Approve with minor formatting fix suggestion.


Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR improves attribute argument validation for ZModel schema files by enhancing error messages and adding specific validation for JSON default values. The changes address issue #584 where JSON field default values were not properly validated.

Changes:

  • Enhanced assignableToAttributeParam function to return descriptive error messages instead of just boolean values
  • Added isLiteralJsonString function to validate that JSON field default values are properly formatted JSON string literals
  • Added comprehensive test coverage for JSON default value validation

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

File Description
tests/regression/test/issue-584.test.ts New test file validating that JSON default values must be valid JSON string literals, covering edge cases like null, plain strings, and valid JSON
packages/language/src/validators/attribute-application-validator.ts Refactored validation logic to return structured error objects with descriptive messages; added JSON string literal validation for JSON/typed JSON fields

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In @packages/language/src/validators/attribute-application-validator.ts:
- Around line 453-455: The error string for the validation result (the object
with the error property in attribute-application-validator.ts) contains a
leading newline/whitespace because it uses a multi-line template literal; update
the error value to be a single-line string without leading whitespace (e.g.,
remove the leading newline/indentation from the template literal) so the message
becomes "expected array" or "expected non-array" based on dstIsArray.
🧹 Nitpick comments (1)
tests/regression/test/issue-584.test.ts (1)

1-66: LGTM! Comprehensive regression test for issue #584.

The test suite effectively validates the JSON default value validation logic:

  • Correctly rejects non-JSON-string-literal defaults (null, 'hello')
  • Correctly accepts valid JSON string literals ('"hello"', '[{"hello":1}]', 'null')

The test coverage aligns well with the fix in the validator.

💡 Optional: Consider additional edge cases

While the current test coverage is sufficient, you could optionally add tests for:

  • Empty JSON objects: @default('{}')
  • Non-nullable JSON fields: data Json @default('null')
  • Complex nested structures
  • JSON with special characters/unicode

These would provide even more comprehensive coverage but are not essential for this regression fix.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9a62051 and 5a51937.

📒 Files selected for processing (2)
  • packages/language/src/validators/attribute-application-validator.ts
  • tests/regression/test/issue-584.test.ts
🧰 Additional context used
🧠 Learnings (4)
📚 Learning: 2025-11-26T01:55:04.540Z
Learnt from: CR
Repo: zenstackhq/zenstack-v3 PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-26T01:55:04.540Z
Learning: Applies to tests/e2e/**/*.{ts,tsx} : E2E tests should validate real-world schema compatibility with established projects

Applied to files:

  • tests/regression/test/issue-584.test.ts
📚 Learning: 2025-11-26T01:55:04.540Z
Learnt from: CR
Repo: zenstackhq/zenstack-v3 PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-26T01:55:04.540Z
Learning: Applies to tests/**/type*.{ts,tsx} : Ensure TypeScript inference and type coverage are validated through type coverage tests

Applied to files:

  • tests/regression/test/issue-584.test.ts
📚 Learning: 2025-11-26T01:55:04.540Z
Learnt from: CR
Repo: zenstackhq/zenstack-v3 PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-26T01:55:04.540Z
Learning: Applies to packages/zenstackhq/orm/**/*.test.{ts,tsx} : ORM package tests should include comprehensive client API tests and policy tests

Applied to files:

  • tests/regression/test/issue-584.test.ts
📚 Learning: 2025-12-30T15:07:06.254Z
Learnt from: mwillbanks
Repo: zenstackhq/zenstack-v3 PR: 550
File: packages/orm/src/client/crud/operations/base.ts:158-159
Timestamp: 2025-12-30T15:07:06.254Z
Learning: Do not use ts-expect-error in production code within the zenstackhq/zenstack-v3 repo (e.g., packages/*). Use explicit type annotations, targeted type assertions, or refactor to resolve the type error. ts-expect-error may be acceptable only in test files for stubbing or temporary silencing. Ensure production code is type-safe and maintainable.

Applied to files:

  • packages/language/src/validators/attribute-application-validator.ts
🧬 Code graph analysis (1)
tests/regression/test/issue-584.test.ts (1)
packages/testtools/src/client.ts (1)
  • createTestClient (101-248)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: Agent
  • GitHub Check: CodeQL analysis (javascript-typescript)
  • GitHub Check: build-test (22.x, postgresql)
  • GitHub Check: build-test (22.x, sqlite)
🔇 Additional comments (4)
packages/language/src/validators/attribute-application-validator.ts (4)

106-110: LGTM! Improved error reporting.

The refactor to use structured results enables precise error messages for each validation failure, improving developer experience.


395-405: LGTM! Well-structured discriminated union.

The function signature change provides better type safety and enables detailed error reporting. The constants for success and error cases improve maintainability.


418-430: LGTM! Core fix for issue #584.

The JSON field validation correctly enforces Prisma's design requirement that @default values for JSON fields must be JSON string literals (e.g., 'null', '"hello"', '[1,2,3]') rather than raw values. The error message is clear and actionable.


607-617: LGTM! Well-implemented JSON validation helper.

The function correctly validates JSON string literals by attempting to parse them. Since this runs only during schema validation (not at runtime), the performance characteristics of JSON.parse are acceptable.

@claude
Copy link

claude bot commented Jan 11, 2026

Claude finished @ymc9's task —— View job


Code Review Complete ✅

Reviewed PR that fixes issue #584 - improving attribute argument assignability check.

Todo List:

  • Read and analyze changed files
  • Review code quality and best practices
  • Check for potential bugs or issues
  • Evaluate performance considerations
  • Assess security concerns
  • Review test coverage
  • Provide comprehensive feedback

Code Quality & Best Practices ✅

Excellent improvements overall! The refactor significantly enhances error reporting and maintainability:

  1. Better Error Messaging: Changed from generic "Value is not assignable to parameter" to specific, actionable error messages like "expected a JSON string literal", "expected an array of field references", etc.

  2. Clean Return Type: The discriminated union return type {result: true} | {result: false; error: string} is much cleaner than the previous boolean return with side effects.

  3. Consistent Error Handling: All error paths now return descriptive messages, making debugging much easier for users.

JSON Default Value Validation 🎯

The core improvement correctly addresses JSON field default validation:

Before (packages/language/src/validators/attribute-application-validator.ts:418-421):

const dstIsTypedJson = hasAttribute(attr.$container, '@json');
if (dstIsTypedJson && attr.decl.ref?.name === '@default') {
    return argResolvedType.decl === 'String';
}

After (packages/language/src/validators/attribute-application-validator.ts:420-430):

const dstIsJson = attr.$container.type.type === 'Json' || hasAttribute(attr.$container, '@json');
if (dstIsJson && attr.decl.ref?.name === '@default') {
    if (isLiteralJsonString(arg.value)) {
        return success;
    } else {
        return {
            result: false,
            error: 'expected a JSON string literal',
        };
    }
}

✅ Key Improvements:

  • Now validates both Json field type AND @json attribute (was missing Json type check)
  • Actually validates that the string contains valid JSON using isLiteralJsonString() helper
  • Provides clear error message instead of generic failure

Test Coverage ✅

The test suite in tests/regression/test/issue-584.test.ts:5-65 is comprehensive:

  • ✅ Tests invalid cases: null literal and plain string 'hello'
  • ✅ Tests valid cases: JSON string '"hello"', JSON array '[{"hello":1}]', JSON null 'null'
  • ✅ Uses realistic ZModel schemas with proper field definitions
  • ✅ Uses createTestClient() to validate end-to-end behavior

Minor Suggestions

  1. Helper Function Location (packages/language/src/validators/attribute-application-validator.ts:607-617): The isLiteralJsonString() helper is well-implemented with proper error handling, but consider moving to a shared utilities module if JSON validation is needed elsewhere.

  2. Error Message Formatting (packages/language/src/validators/attribute-application-validator.ts:453-455): There's a formatting issue with extra whitespace:

error: `
                    expected ${dstIsArray ? 'array' : 'non-array'}`,

Should be:

error: `expected ${dstIsArray ? 'array' : 'non-array'}`,
  1. Array Logic Improvement (packages/language/src/validators/attribute-application-validator.ts:466): Good change from find() to some() for better semantic clarity when checking if any items are invalid.

Security & Performance ✅

  • Security: The JSON.parse() call in isLiteralJsonString() is safely wrapped in try-catch
  • Performance: Changes are minimal and don't introduce any performance concerns
  • Memory: No memory leaks or unnecessary object allocations

Overall Assessment 🎉

This is a high-quality fix that:

  • ✅ Addresses the root issue comprehensively
  • ✅ Significantly improves developer experience with better error messages
  • ✅ Maintains backward compatibility
  • ✅ Includes thorough test coverage
  • ✅ Follows existing code patterns and conventions

Recommendation: Approve with minor formatting fix suggestion.


@claude
Copy link

claude bot commented Jan 11, 2026

Claude finished @ymc9's task —— View job


I'll analyze this PR and provide comprehensive feedback on code quality, potential issues, performance, security, and test coverage.

Todo List:

  • Read and analyze changed files
  • Review code quality and best practices
  • Check for potential bugs or issues
  • Evaluate performance considerations
  • Assess security concerns
  • Review test coverage
  • Provide comprehensive feedback

Code Review Complete ✅

Reviewed PR that fixes issue #584 - improving attribute argument assignability check.

Todo List:

  • Read and analyze changed files
  • Review code quality and best practices
  • Check for potential bugs or issues
  • Evaluate performance considerations
  • Assess security concerns
  • Review test coverage
  • Provide comprehensive feedback

Code Quality & Best Practices ✅

Excellent improvements overall! The refactor significantly enhances error reporting and maintainability:

  1. Better Error Messaging: Changed from generic "Value is not assignable to parameter" to specific, actionable error messages like "expected a JSON string literal", "expected an array of field references", etc.

  2. Clean Return Type: The discriminated union return type {result: true} | {result: false; error: string} is much cleaner than the previous boolean return with side effects.

  3. Consistent Error Handling: All error paths now return descriptive messages, making debugging much easier for users.

JSON Default Value Validation 🎯

The core improvement correctly addresses JSON field default validation:

Before (packages/language/src/validators/attribute-application-validator.ts:418-421):

const dstIsTypedJson = hasAttribute(attr.$container, '@json');
if (dstIsTypedJson && attr.decl.ref?.name === '@default') {
    return argResolvedType.decl === 'String';
}

After (packages/language/src/validators/attribute-application-validator.ts:420-430):

const dstIsJson = attr.$container.type.type === 'Json' || hasAttribute(attr.$container, '@json');
if (dstIsJson && attr.decl.ref?.name === '@default') {
    if (isLiteralJsonString(arg.value)) {
        return success;
    } else {
        return {
            result: false,
            error: 'expected a JSON string literal',
        };
    }
}

✅ Key Improvements:

  • Now validates both Json field type AND @json attribute (was missing Json type check)
  • Actually validates that the string contains valid JSON using isLiteralJsonString() helper
  • Provides clear error message instead of generic failure

Test Coverage ✅

The test suite in tests/regression/test/issue-584.test.ts:5-65 is comprehensive:

  • ✅ Tests invalid cases: null literal and plain string 'hello'
  • ✅ Tests valid cases: JSON string '"hello"', JSON array '[{"hello":1}]', JSON null 'null'
  • ✅ Uses realistic ZModel schemas with proper field definitions
  • ✅ Uses createTestClient() to validate end-to-end behavior

Minor Suggestions

  1. Helper Function Location (packages/language/src/validators/attribute-application-validator.ts:607-617): The isLiteralJsonString() helper is well-implemented with proper error handling, but consider moving to a shared utilities module if JSON validation is needed elsewhere.

  2. Error Message Formatting (packages/language/src/validators/attribute-application-validator.ts:453-455): There's a formatting issue with extra whitespace:

error: `
                    expected ${dstIsArray ? 'array' : 'non-array'}`,

Should be:

error: `expected ${dstIsArray ? 'array' : 'non-array'}`,
  1. Array Logic Improvement (packages/language/src/validators/attribute-application-validator.ts:466): Good change from find() to some() for better semantic clarity when checking if any items are invalid.

Security & Performance ✅

  • Security: The JSON.parse() call in isLiteralJsonString() is safely wrapped in try-catch
  • Performance: Changes are minimal and don't introduce any performance concerns
  • Memory: No memory leaks or unnecessary object allocations

Overall Assessment 🎉

This is a high-quality fix that:

  • ✅ Addresses the root issue comprehensively
  • ✅ Significantly improves developer experience with better error messages
  • ✅ Maintains backward compatibility
  • ✅ Includes thorough test coverage
  • ✅ Follows existing code patterns and conventions

Recommendation: Approve with minor formatting fix suggestion.


@claude
Copy link

claude bot commented Jan 11, 2026

Claude finished @ymc9's task —— View job


Code Review for PR #588

I'll analyze this PR that fixes issue #584 - improving attribute argument assignability check.

Todo List:

  • Read and analyze changed files
  • Review code quality and best practices
  • Check for potential bugs or issues
  • Evaluate performance considerations
  • Assess security concerns
  • Review test coverage
  • Provide comprehensive feedback

Code Quality & Best Practices ✅

Excellent improvements overall! The refactor significantly enhances error reporting and maintainability:

  1. Better Error Messaging: Changed from generic "Value is not assignable to parameter" to specific, actionable error messages like "expected a JSON string literal", "expected an array of field references", etc.

  2. Clean Return Type: The discriminated union return type {result: true} | {result: false; error: string} is much cleaner than the previous boolean return with side effects.

  3. Consistent Error Handling: All error paths now return descriptive messages, making debugging much easier for users.

JSON Default Value Validation 🎯

The core improvement correctly addresses JSON field default validation:

Before (packages/language/src/validators/attribute-application-validator.ts:418-421):

const dstIsTypedJson = hasAttribute(attr.$container, '@json');
if (dstIsTypedJson && attr.decl.ref?.name === '@default') {
    return argResolvedType.decl === 'String';
}

After (packages/language/src/validators/attribute-application-validator.ts:420-430):

const dstIsJson = attr.$container.type.type === 'Json' || hasAttribute(attr.$container, '@json');
if (dstIsJson && attr.decl.ref?.name === '@default') {
    if (isLiteralJsonString(arg.value)) {
        return success;
    } else {
        return {
            result: false,
            error: 'expected a JSON string literal',
        };
    }
}

✅ Key Improvements:

  • Now validates both Json field type AND @json attribute (was missing Json type check)
  • Actually validates that the string contains valid JSON using isLiteralJsonString() helper
  • Provides clear error message instead of generic failure

Test Coverage ✅

The test suite in tests/regression/test/issue-584.test.ts:5-65 is comprehensive:

  • ✅ Tests invalid cases: null literal and plain string 'hello'
  • ✅ Tests valid cases: JSON string '"hello"', JSON array '[{"hello":1}]', JSON null 'null'
  • ✅ Uses realistic ZModel schemas with proper field definitions
  • ✅ Uses createTestClient() to validate end-to-end behavior

Minor Suggestions

  1. Helper Function Location (packages/language/src/validators/attribute-application-validator.ts:607-617): The isLiteralJsonString() helper is well-implemented with proper error handling, but consider moving to a shared utilities module if JSON validation is needed elsewhere.

  2. Error Message Formatting (packages/language/src/validators/attribute-application-validator.ts:453-455): There's a formatting issue with extra whitespace:

error: `
                    expected ${dstIsArray ? 'array' : 'non-array'}`,

Should be:

error: `expected ${dstIsArray ? 'array' : 'non-array'}`,
  1. Array Logic Improvement (packages/language/src/validators/attribute-application-validator.ts:466): Good change from find() to some() for better semantic clarity when checking if any items are invalid.

Security & Performance ✅

  • Security: The JSON.parse() call in isLiteralJsonString() is safely wrapped in try-catch
  • Performance: Changes are minimal and don't introduce any performance concerns
  • Memory: No memory leaks or unnecessary object allocations

Overall Assessment 🎉

This is a high-quality fix that:

  • ✅ Addresses the root issue comprehensively
  • ✅ Significantly improves developer experience with better error messages
  • ✅ Maintains backward compatibility
  • ✅ Includes thorough test coverage
  • ✅ Follows existing code patterns and conventions

Recommendation: Approve with minor formatting fix suggestion.


Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
packages/language/src/validators/attribute-application-validator.ts (2)

472-490: Simplify the array-of-field-references check for readability.
The double-negative !some(!...) is correct but harder to scan.

Proposed diff
-            if (
-                isArrayExpr(arg.value) &&
-                !arg.value.items.some((item) => !isReferenceExpr(item) || !isDataField(item.target.ref))
-            ) {
+            if (
+                isArrayExpr(arg.value) &&
+                arg.value.items.every((item) => isReferenceExpr(item) && isDataField(item.target.ref))
+            ) {
                 return success;
             } else {
                 return { result: false, error: 'expected an array of field references' };
             }

619-629: isLiteralJsonString is a good focused helper; consider a clearer error phrase.
Right now failures show “expected a JSON string literal”, but the actual requirement is “a string literal containing valid JSON” (important for JSON string values, which require escaped quotes).

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9913d04 and 393f065.

📒 Files selected for processing (2)
  • packages/language/src/validators/attribute-application-validator.ts
  • packages/sdk/src/ts-schema-generator.ts
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-12-30T15:07:06.254Z
Learnt from: mwillbanks
Repo: zenstackhq/zenstack-v3 PR: 550
File: packages/orm/src/client/crud/operations/base.ts:158-159
Timestamp: 2025-12-30T15:07:06.254Z
Learning: Do not use ts-expect-error in production code within the zenstackhq/zenstack-v3 repo (e.g., packages/*). Use explicit type annotations, targeted type assertions, or refactor to resolve the type error. ts-expect-error may be acceptable only in test files for stubbing or temporary silencing. Ensure production code is type-safe and maintainable.

Applied to files:

  • packages/language/src/validators/attribute-application-validator.ts
  • packages/sdk/src/ts-schema-generator.ts
🧬 Code graph analysis (1)
packages/sdk/src/ts-schema-generator.ts (1)
packages/language/src/generated/ast.ts (1)
  • isNullExpr (593-595)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: claude-review
  • GitHub Check: build-test (22.x, postgresql)
  • GitHub Check: build-test (22.x, sqlite)
🔇 Additional comments (7)
packages/sdk/src/ts-schema-generator.ts (3)

608-666: LGTM! Null default value handling implemented correctly.

The explicit null check on line 610 correctly precedes the object check on line 614. This ordering is essential because typeof null === 'object' in JavaScript, so checking for null first prevents it from being mishandled as an object. The generated ExpressionUtils._null() call is consistent with the pattern used in createNullExpression() (line 1255).

This properly addresses the PR objective of handling nullable JSON fields with @default(null).


729-747: LGTM! Return type correctly updated to include null.

The expanded return type properly distinguishes between:

  • undefined: No @default attribute present
  • null: Explicit @default(null) value
  • Other types: Actual default values

This enhances type safety and aligns with the new null handling logic.


749-778: LGTM! Null expression handling and error message improved.

The explicit handling of isNullExpr (lines 773-774) correctly returns null, which propagates through the mapping flow. The updated error message on line 776 is an improvement—it's more generic and doesn't assume this method is only used for default values, making it more maintainable as the codebase evolves.

The return type update to include | null properly reflects the new capability.

packages/language/src/validators/attribute-application-validator.ts (4)

25-27: Importing isStringLiteral is a clean way to type-guard JSON-default literals.


107-111: Nice: propagate the precise type-mismatch error to the user and short-circuit.
This should make schema diagnostics materially better than the prior boolean result.


396-414: Discriminated union return for assignableToAttributeParam is a solid API upgrade.
The { result: false; error: string } shape is easy to extend without widening call-site logic.


416-446: The validator code is correct and the concern is based on a misunderstanding.

Issue #584 test explicitly validates that @default(null) should be rejected and only @default('null') (a JSON string literal containing null) should be accepted. This is the intended design—JSON default values must be strings containing valid JSON, following Prisma's convention.

The test cases confirm:

  • @default(null) → REJECTED with "expected a JSON string literal" ✓ (correct)
  • @default('null') → ACCEPTED ✓ (correct)
  • @default('"hello"') → ACCEPTED ✓ (correct)

The code is working as designed. No changes needed.

Likely an incorrect or invalid review comment.

@ymc9 ymc9 merged commit 6bf2b51 into dev Jan 11, 2026
6 checks passed
@ymc9 ymc9 deleted the fix/issue-584 branch January 11, 2026 08:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant