StefanTerdell / zod-to-json-schema

Converts Zod schemas to Json schemas
ISC License
854 stars 67 forks source link

Generated regex cannot be used with unicode flag #93

Closed rbuetzer closed 9 months ago

rbuetzer commented 10 months ago

It appears to me that the regex patterns generated by zodToJsonSchema cannot always handle the regex unicode flag.

Steps to reproduce

Run the follwoing code (Example on StackBlitz)

const zodSchema = z.string().includes("@");
const jsonSchema = zodToJsonSchema(zodSchema);

const regex = new RegExp(jsonSchema.pattern, 'u');

Observed behavior

Expected behavior

No runtime error is thrown

Analysis

The generated JSON schema looks like this:

{
  "type": "string",
  "pattern": "\\@",
  "$schema": "http://json-schema.org/draft-07/schema#"
}

The problem is, that the @ is escaped.

The MDN docs on \ state:

Escape sequences like \:, -, \@ will be equivalent to their literal, unescaped character equivalents in regular expressions. However, in regular expressions with the unicode flag, these will cause an invalid identity escape error.

StefanTerdell commented 9 months ago

JFC I hate regex

Would adding an option to not escape special characters be a solution?

StefanTerdell commented 9 months ago

Try the new patternStrategy option if you run into this.