StefanTerdell / zod-to-json-schema

Converts Zod schemas to Json schemas
ISC License
917 stars 76 forks source link

RegExp is not being parsed correctly into pattern property #154

Open kylekirkby opened 1 week ago

kylekirkby commented 1 week ago

We've got a custom URL schema that is failing to be correctly translated to a pattern property.

export const urlRegex =
  /^((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=+$,\w]+@)?[A-Za-z0-9.-]+|(?:www\.|[-;:&=+$,\w]+@)[A-Za-z0-9.-]+)((?:\/[+~%,/.\w\-_]*)?\??(?:[-+=&;%@.\w:()_]*)#?(?:[.!/\\\w]*))?)/;

export const URLSchema = z
  .string()
  .min(1)
  .max(1000)
  .regex(urlRegex, { message: "Please enter a valid URL" })
  .brand("url");

When loading Swagger UI we're getting unknown escape sequence.

It looks like we need to double escape backslashes in JSON?

Cheers!

StefanTerdell commented 1 week ago

I'm able to successfully construct the regexp from the JSON schema produced from your example, so I need some help reproducing this @kylekirkby

Could you check the Swagger UI code to see what specifically produces the error?

StefanTerdell commented 1 week ago

Added some tests for it here btw https://github.com/StefanTerdell/zod-to-json-schema/blob/master/test/issues.test.ts#L48