hey-api / openapi-ts

🚀 The OpenAPI to TypeScript codegen. Generate clients, SDKs, validators, and more. Support: @mrlubos
https://heyapi.dev
Other
1.39k stars 107 forks source link

Const with newlines is broken #1287

Closed xtyrrell closed 3 days ago

xtyrrell commented 1 week ago

Description

An OpenAPI schema that includes a const with newlines is not processed correctly. open-api-ts produces an invalid types.gen.ts.

For example, the following schema (at DEFAULT_INSTRUCTIONS):

{
  "openapi": "3.1.0",
  "info": {
    "title": "app",
    "version": "0.1.0"
  },
  "paths": {
    "/api/constants/": {
      "get": {
        "summary": "Get Constants",
        "description": "Get constants for the frontend",
        "operationId": "get_constants_api_constants__get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "DEFAULT_INSTRUCTIONS": {
                      "const": "First line.\n\nSecond line.\n\nPS: I love you."
                    }
                  },
                  "type": "object"
                }
              }
            }
          }
        }
      }
    }
  }
}

produces this invalid types.gen.ts file.

// This file is auto-generated by @hey-api/openapi-ts

export type GetConstantsApiConstantsGetResponse = ({
    DEFAULT_INSTRUCTIONS?: "First line.

Second line.

PS: I love you.";
});

export type GetConstantsApiConstantsGetError = unknown;

This is invalid because a double-quote quoted string cannot contain newlines in TypeScript.

Screenshot 2024-11-14 at 13 27 07

A fix for this could be using ` backtick characters, which are allowed to contain newlines in TypeScript, rather than " double quotes. If minimising changes to generated files is a goal, this could be done only for those const values which include newlines (leaving others to use double quotes).

Reproducible example or configuration

https://stackblitz.com/edit/hey-api-example-qyowue?file=src%2Fclient%2Ftypes.gen.ts

stackblitz[bot] commented 1 week ago

Fix this issue in StackBlitz Codeflow Start a new pull request in StackBlitz Codeflow.

mrlubos commented 1 week ago

Hey @xtyrrell, thanks for reporting. Which approach would you choose if you were to fix it manually in your code?

xtyrrell commented 6 days ago

I would use backticks to quote strings that contain newlines, and leave other strings as is.

mrlubos commented 3 days ago

@xtyrrell this works as expected in the experimental parser, so I will mark this as resolved!