Apollo314 / openapi-to-zod

MIT License
3 stars 2 forks source link

Correct handling of patterns where slashes are in the spec? #4

Open robogeek opened 11 months ago

robogeek commented 11 months ago

The spec I'm using has specified some strings with a pattern field where the regular expression is delineated with slashes. For example:

    duration:
      type: string
      pattern: /^(-?)P(?=\d|T\d)(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)([DW]))?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+(?:\.\d+)?)S)?)?$/
      description: duration in ISO 8601 format
      example: PT1H
      default: PT0S

I was not able to find if this is legitimate OpenAPI. In the Swagger specification it shows a quoted string with no slashes, rather than an unquoted string with slashes like here.

The generated code for the above is:

import { z } from "zod";

export default z
  .string()
  .regex(
    new RegExp(
      "/^(-?)P(?=\\d|T\\d)(?:(\\d+)Y)?(?:(\\d+)M)?(?:(\\d+)([DW]))?(?:T(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+(?:\\.\\d+)?)S)?)?$/"
    )
  )
  .describe("duration in ISO 8601 format")
  .default("PT0S");

This fails on recognizing the string I fed it. The RegExp object is defined (in MSDN) to take either a quoted string with no slashes, or an unquoted string with slashes. The latter is directly recognized in JavaScript as a regular expression.

QUESTION: Is an unquoted string with slashes allowed in OpenAPI to specify a regular expression?

If so, then this library should recognize that case, and pass through a RegExp literal.

Apollo314 commented 11 months ago

Hello, this is just a simple cli tool to automate https://github.com/StefanTerdell/json-schema-to-zod for all the components of an OpenAPI scheme after dereferencing them. If you think there is something at fault at parsing the schema, that repository is probably the place to address it.

However, I don't think OpenAPI allows unquoted regexes. Because they don't even get parsed by json parsers or yaml parsers as regex objects. They are just assumed strings.