Skip to content

Add Khmer locale support to Zod and update documentation #4447

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 28, 2025

Conversation

SuuSoJeat
Copy link
Contributor

@SuuSoJeat SuuSoJeat commented May 20, 2025

Added initial Khmer locale.

Summary by CodeRabbit

  • New Features

    • Added support for the Khmer (kh) locale in error messages.
  • Documentation

    • Updated the error customization guide to include Khmer as a supported locale.

Copy link
Contributor

coderabbitai bot commented May 20, 2025

Walkthrough

A new Khmer (kh) locale was added to the error message system, including a full set of Khmer translations for validation errors. The documentation was updated to list Khmer as a supported locale, and the locale was exported for use in the main locales index.

Changes

File(s) Change Summary
packages/zod/src/v4/locales/kh.ts Added new Khmer locale module with localized error messages and export of locale error map.
packages/zod/src/v4/locales/index.ts Exported the new kh locale from the locales index.
packages/docs/content/error-customization.mdx Updated documentation to include Khmer (kh) in the list of available locales.

Poem

In the land of Zod, a new tongue appears,
Khmer joins the chorus, dispelling old fears.
Errors now speak in a script fresh and bright,
Guiding with wisdom, in day and in night.
🎉🌏✨
Welcome, Khmer, to the validation delight!

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate Unit Tests
  • Create PR with Unit Tests
  • Commit Unit Tests in branch feature/khmer-language
  • Post Copyable Unit Tests in Comment

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@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: 2

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 66ee76c and 1aa1b84.

📒 Files selected for processing (3)
  • packages/docs/content/error-customization.mdx (1 hunks)
  • packages/zod/src/v4/locales/index.ts (1 hunks)
  • packages/zod/src/v4/locales/kh.ts (1 hunks)
🔇 Additional comments (3)
packages/docs/content/error-customization.mdx (1)

362-362: Nice addition! The Khmer locale looks great in the docs.

The Khmer locale has been properly added to the documentation in the correct alphabetical position between Japanese and Korean.

packages/zod/src/v4/locales/index.ts (1)

18-18: LGTM! Export added in the right spot.

The Khmer locale export has been correctly added in alphabetical order between Japanese and Korean locales.

packages/zod/src/v4/locales/kh.ts (1)

1-127: Great work on the Khmer locale implementation!

Overall, the implementation looks good and follows the structure of other locale files. The translations seem comprehensive, covering all the error codes needed for Zod validation messages.

Comment on lines +111 to +112
case "invalid_union":
return `ទិន្នន័យមិនត្រឹមត្រូវ`;
Copy link
Contributor

@coderabbitai coderabbitai bot May 20, 2025

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Consider adding more details to the 'invalid_union' error message.

The error message for 'invalid_union' is currently very generic. Most locale implementations provide more detailed information about why the union validation failed.

You might want to enhance this message to include more details about the union validation failure, similar to other locales. For example, you could mention that none of the union schemas matched the input.

🤖 Prompt for AI Agents
In packages/zod/src/v4/locales/kh.ts around lines 111 to 112, the
'invalid_union' error message is too generic. Update the message to provide more
detail, such as indicating that none of the union schemas matched the input, to
align with other locale implementations and improve clarity for users.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I'm following other locales, especially the English locale.

Copy link
Contributor

Choose a reason for hiding this comment

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

🧩 Analysis chain

Searching for locale files...
packages/zod/src/v4/locales/de.ts
packages/zod/src/v4/locales/en.ts
packages/zod/src/v4/locales/es.ts
packages/zod/src/v4/locales/fr.ts
packages/zod/src/v4/locales/he.ts
packages/zod/src/v4/locales/hi.ts
packages/zod/src/v4/locales/index.ts
packages/zod/src/v4/locales/it.ts
packages/zod/src/v4/locales/ja.ts
packages/zod/src/v4/locales/kh.ts
packages/zod/src/v4/locales/ko.ts
packages/zod/src/v4/locales/nb.ts
packages/zod/src/v4/locales/nl.ts
packages/zod/src/v4/locales/pt.ts
packages/zod/src/v4/locales/ru.ts
packages/zod/src/v4/locales/tr.ts
packages/zod/src/v4/locales/uk.ts
packages/zod/src/v4/locales/zh.ts

Examining English locale implementation of 'invalid_union'...
98: case "invalid_union":
99- return "Invalid input";

Checking other locale implementations of 'invalid_union'...

======= packages/zod/src/v4/locales/de.ts =======
115: case "invalid_union":
116- return "Ungültige Eingabe";

======= packages/zod/src/v4/locales/es.ts =======
98: case "invalid_union":
99- return "Entrada inválida";

======= packages/zod/src/v4/locales/fr.ts =======
98: case "invalid_union":
99- return "Entrée invalide";

======= packages/zod/src/v4/locales/he.ts =======
107: case "invalid_union":
108- return "קלט לא חוקי";

======= packages/zod/src/v4/locales/hi.ts =======
99: case "invalid_union":
100- return "अमान्य इनपुट";

======= packages/zod/src/v4/locales/it.ts =======
98: case "invalid_union":
99- return "Input non valido";

======= packages/zod/src/v4/locales/ja.ts =======
98: case "invalid_union":
99- return "無効な入力です";

======= packages/zod/src/v4/locales/ko.ts =======
98: case "invalid_union":
99- return "유효하지 않은 입력입니다";

======= packages/zod/src/v4/locales/nb.ts =======
97: case "invalid_union":
98- return "Ugyldig inntasting";

======= packages/zod/src/v4/locales/nl.ts =======
115: case "invalid_union":
116- return "Ongeldige invoer";

======= packages/zod/src/v4/locales/pt.ts =======
98: case "invalid_union":
99- return "Entrada inválida";

======= packages/zod/src/v4/locales/ru.ts =======
98: case "invalid_union":
99- return "Неверные данные";

======= packages/zod/src/v4/locales/tr.ts =======
100: case "invalid_union":
101- return "Geçersiz girdi";

======= packages/zod/src/v4/locales/uk.ts =======
98: case "invalid_union":
99- return "Некоректні дані";

======= packages/zod/src/v4/locales/zh.ts =======
98: case "invalid_union":
99- return "无效输入";

@SuuSoJeat You're absolutely right. After checking all locale implementations, I can confirm that your implementation follows the same pattern as the English locale and all other locales. They all use simple, generic messages for 'invalid_union' cases (e.g., "Invalid input" in English).

Sorry for the unnecessary nitpick. Your implementation is perfectly consistent with the established pattern in the codebase. Thanks for maintaining this consistency!


🏁 Script executed:

#!/bin/bash

# Find all locale files
echo "Searching for locale files..."
find packages/zod/src -name "*.ts" -path "*/locales/*" | sort

# First, look at the English locale implementation specifically for 'invalid_union' error handling
echo -e "\nExamining English locale implementation of 'invalid_union'..."
grep -n -A 3 -B 0 "case \"invalid_union\"" packages/zod/src/v4/locales/en.ts

# Look at other locale implementations of 'invalid_union' for comparison
echo -e "\nChecking other locale implementations of 'invalid_union'..."
for locale_file in $(find packages/zod/src -name "*.ts" -path "*/locales/*" -not -name "kh.ts" -not -name "index.ts"); do
  echo -e "\n======= $locale_file ======="
  grep -n -A 3 -B 0 "case \"invalid_union\"" $locale_file
done

Length of output: 19879


@SuuSoJeat You're absolutely right. After checking all locale implementations, I can confirm that your Khmer implementation follows the same pattern as the English locale and other locales. Most locales use a simple, generic message for 'invalid_union' errors - just as you've done.

Sorry for the unnecessary nitpick. Your implementation is perfectly consistent with the codebase standards.


🧬 Code Graph Analysis Results

Relevant snippet from packages/zod/src/v4/core/errors.ts (lines 127-133)

export type $ZodStringFormatIssues =
  | $ZodIssueStringCommonFormats
  | $ZodIssueStringInvalidRegex
  | $ZodIssueStringInvalidJWT
  | $ZodIssueStringStartsWith
  | $ZodIssueStringEndsWith
  | $ZodIssueStringIncludes;

This type union defines the possible string format issue types that the Khmer locale error map handles in the invalid_format case.


Relevant snippet from packages/zod/src/v3/types.ts (lines 247-290)

"~validate"(data: unknown): StandardSchemaV1.Result<Output> | Promise<StandardSchemaV1.Result<Output>> {
    const ctx: ParseContext = {
      common: {
        issues: [],
        async: !!(this["~standard"] as any).async,
      },
      path: [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data,
      parsedType: getParsedType(data),
    };

    if (!(this["~standard"] as any).async) {
      try {
        const result = this._parseSync({ data, path: [], parent: ctx });
        return isValid(result)
          ? {
              value: result.value,
            }
          : {
              issues: ctx.common.issues,
            };
      } catch (err: any) {
        if ((err as Error)?.message?.toLowerCase()?.includes("encountered")) {
          (this["~standard"] as any).async = true;
        }
        (ctx as any).common = {
          issues: [],
          async: true,
        };
      }
    }

    return this._parseAsync({ data, path: [], parent: ctx }).then((result) =>
      isValid(result)
        ? {
            value: result.value,
          }
        : {
            issues: ctx.common.issues,
          }
    );
  }

This method shows how validation is performed, including synchronous and asynchronous parsing, and how issues are collected and returned. It references schemaErrorMap which is related to locale-specific error messages like those defined in the Khmer locale file.


These snippets provide context on the types of string format issues handled and the validation flow that would trigger the error messages defined in the Khmer locale file.

Comment on lines +82 to +94
if (sizing)
return `ធំពេក៖ ត្រូវការ ${issue.origin ?? "តម្លៃ"} ${adj} ${issue.maximum.toString()} ${sizing.unit ?? "ធាតុ"}`;
return `ធំពេក៖ ត្រូវការ ${issue.origin ?? "តម្លៃ"} ${adj} ${issue.maximum.toString()}`;
}
case "too_small": {
const adj = issue.inclusive ? ">=" : ">";
const sizing = getSizing(issue.origin);
if (sizing) {
return `តូចពេក៖ ត្រូវការ ${issue.origin} ${adj} ${issue.minimum.toString()} ${sizing.unit}`;
}

return `តូចពេក៖ ត្រូវការ ${issue.origin} ${adj} ${issue.minimum.toString()}`;
}
Copy link
Contributor

@coderabbitai coderabbitai bot May 20, 2025

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Fix inconsistency between 'too_big' and 'too_small' error handling.

There's an inconsistency in how fallback values are handled between the 'too_big' and 'too_small' cases:

  1. In 'too_big', there are fallbacks for origin and unit (issue.origin ?? "តម្លៃ" and sizing.unit ?? "ធាតុ")
  2. In 'too_small', these fallbacks are missing, which could lead to undefined values in error messages
  if (sizing) {
-    return `តូចពេក៖ ត្រូវការ ${issue.origin} ${adj} ${issue.minimum.toString()} ${sizing.unit}`;
+    return `តូចពេក៖ ត្រូវការ ${issue.origin ?? "តម្លៃ"} ${adj} ${issue.minimum.toString()} ${sizing.unit ?? "ធាតុ"}`;
  }

- return `តូចពេក៖ ត្រូវការ ${issue.origin} ${adj} ${issue.minimum.toString()}`;
+ return `តូចពេក៖ ត្រូវការ ${issue.origin ?? "តម្លៃ"} ${adj} ${issue.minimum.toString()}`;
🤖 Prompt for AI Agents
In packages/zod/src/v4/locales/kh.ts between lines 82 and 94, the 'too_small'
case lacks fallback values for issue.origin and sizing.unit, unlike the
'too_big' case which uses defaults to prevent undefined values. Update the
'too_small' case to include the same fallback logic by using issue.origin ??
"តម្លៃ" and sizing.unit ?? "ធាតុ" in the returned strings to ensure consistency
and avoid undefined outputs.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I'm following other locales, especially the English locale.

Copy link
Contributor

Choose a reason for hiding this comment

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check the English locale implementation for comparison
if [ -f packages/zod/src/v4/locales/en.ts ]; then
  echo "English locale found at v4 path. Showing implementation of too_big and too_small cases:"
  grep -A15 "too_big\|too_small" packages/zod/src/v4/locales/en.ts
else
  echo "English locale not found at v4 path, checking other paths"
  # Try the non-v4 path
  if [ -f packages/zod/src/locales/en.ts ]; then
    echo "English locale found at non-v4 path. Showing implementation of too_big and too_small cases:"
    grep -A15 "too_big\|too_small" packages/zod/src/locales/en.ts
  else
    echo "Could not find English locale at common paths. Listing available locale files:"
    find packages/zod/src -name "*.ts" | grep -i "locale"
  fi
fi

Length of output: 1441


@SuuSoJeat I see what you mean now! Looking at the English locale implementation, I can confirm that your Khmer locale is indeed consistent with it:

// English locale - too_small case
case "too_small": {
  const adj = issue.inclusive ? ">=" : ">";
  const sizing = getSizing(issue.origin);
  if (sizing) {
    return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`;
  }

  return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`;
}

The English locale doesn't use fallbacks for issue.origin or sizing.unit in the "too_small" case either, so your implementation correctly follows the existing pattern. Thanks for clarifying!


🧬 Code Graph Analysis Results

Possibly relevant snippets from packages/zod/src/v4/core/errors.ts (lines 127-133)

export type $ZodStringFormatIssues =
  | $ZodIssueStringCommonFormats
  | $ZodIssueStringInvalidRegex
  | $ZodIssueStringInvalidJWT
  | $ZodIssueStringStartsWith
  | $ZodIssueStringEndsWith
  | $ZodIssueStringIncludes;

This snippet defines the TypeScript union type $ZodStringFormatIssues which represents various string format validation issue types. It is relevant because the Khmer locale file references this type when handling invalid_format issues in the error map function.


Possibly relevant snippets from packages/zod/src/v3/types.ts (lines 247-290)

"~validate"(data: unknown): StandardSchemaV1.Result<Output> | Promise<StandardSchemaV1.Result<Output>> {
    const ctx: ParseContext = {
      common: {
        issues: [],
        async: !!(this["~standard"] as any).async,
      },
      path: [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data,
      parsedType: getParsedType(data),
    };

    if (!(this["~standard"] as any).async) {
      try {
        const result = this._parseSync({ data, path: [], parent: ctx });
        return isValid(result)
          ? {
              value: result.value,
            }
          : {
              issues: ctx.common.issues,
            };
      } catch (err: any) {
        if ((err as Error)?.message?.toLowerCase()?.includes("encountered")) {
          (this["~standard"] as any).async = true;
        }
        (ctx as any).common = {
          issues: [],
          async: true,
        };
      }
    }

    return this._parseAsync({ data, path: [], parent: ctx }).then((result) =>
      isValid(result)
        ? {
            value: result.value,
          }
        : {
            issues: ctx.common.issues,
          }
    );
  }

This snippet shows a validation method that uses an error map (schemaErrorMap) to produce validation issues. It is relevant as it demonstrates how error maps like the one defined in the Khmer locale are integrated into the validation process, influencing error message generation.


No other snippets appear directly relevant to understanding or improving the Khmer locale error messages or their structure.

@colinhacks colinhacks merged commit 3c5ffd2 into colinhacks:main May 28, 2025
5 checks passed
@colinhacks
Copy link
Owner

Thank you!!

timorthi pushed a commit to timorthi/zod that referenced this pull request Jun 3, 2025
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.

2 participants
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy